Hibernate – SortedMap Mapping
SortedMap is a map that always maintains its corresponding entries in ascending key order. In Hibernate, using the <map> element and ‘sort’ as ‘natural’ we can maintain the SortedMap. Let us see that by using the one-to-many relationship concept. For example, for a programming language like Java, many books are written. If SortedMap is followed, the books are organized in alphabetical order. Let us see that via a sample project.
Let us create MySQL tables.
-- Main table which has languagename like Java CREATE TABLE `programmingLanguages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `languageName` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`) ); -- Child table that has book details related to a languageId and hence it is referred here -- Via sortedmapping in hibernate, master detail relationship is getting set CREATE TABLE `bookDetails` ( `id` int(11) NOT NULL AUTO_INCREMENT, `bookName` varchar(40) DEFAULT NULL, `authorName` varchar(30) DEFAULT NULL, `languageId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ;
Maven-driven project. Let’s see the pom.xml file.
Let’s start with POJO classes. As two tables are there, let’s have 2 POJO classes each for one table.
Let us see the configuration files now
In the main configuration file, 2 mapping resources are added. Let us see them
Let us go for the main class which does the addition of programming language and books into the MySQL table and listing from there
On running the project, we can see the below output in the console.
Let us see the output explanation in detail
MySQL table output:
In sorted mapping, the index column is a must and it is represented in the MySql output as well. While storing as well, according to the alphabetical order of book name, they are stored in MySQL
Please Login to comment...