Table of contents
1.
Introduction
2.
Example on Hibernate SortedMap mapping
2.1.
Student.java
2.2.
Subject.java
2.3.
Hibernate.cfg.xml
2.4.
Student.hbm.xml
2.5.
Subject.hbm.xml
2.6.
HibernateUtil.java
2.7.
HibernateTest.java
2.8.
StudentDBOperations.java
2.9.
Output
3.
Frequently Asked Questions
3.1.
What distinguishes spring boot from hibernate?
3.2.
What are ORM and JPA?
3.3.
What does Hibernate's lazy loading mean?
3.4.
What is the use of generator class in hibernate?
3.5.
What is Association in Hibernate?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Hibernate SortedMap mapping

Author Komal Shaw
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A map called SortedMap keeps its related items in ascending key order at all times. We may keep the SortedMap in Hibernate by using the <map> element and "sort" as "natural." 

There can be no duplicate elements on the map. The map is sorted either by a Comparator that is normally provided at the time a sorted map is created or by the keys' inherent ordering.

An ordered map can be initialized with java.util.TreeMap, while a SortedMap is mapped with a <map> element in the mapping table.

Let’s dive into Hibernate SortedMap mapping by looking at an example.

Example on Hibernate SortedMap mapping

We need to create the given below pages for SortedMap mapping

  1. Student.java
  2. Subject.java
  3. Hibernate.cfg.xml
  4. Student.hbm.xml
  5. Subject.hbm.xml
  6. HibernateUtil.java
  7. HibernateTest.java
  8. StudentDBOperations.java

Student.java

(We are implementing a class Student, which will be used to persist the objects related to the Student table).

import java.util.SortedMap;
public class Student {
//data members
private int studentId;
private String firstName;
private String lastName;
private String className;
private String rollNo;
private int age;
private SortedMap subjects;
 
public Student(){
 
}
 
public Student(String firstName, String lastName, 
String className, String rollNo, int age){
this.firstName = firstName;
this.lastName = lastName;
this.className = className;
this.rollNo = rollNo;
this.age = age; 
}


  public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public SortedMap getSubjects() {
return subjects;
}
public void setSubjects(SortedMap subjects) {
this.subjects = subjects;
}
}

Subject.java

(We are implementing a class Subject, which will be used to persist the objects related to the Subject table).

public class Subject implements Comparable <String>{
//data members
private int subjectId;
private String subjectName;
 
//no argument constructor
public Subject(){
 
}
 
//argument constructor
public Subject(String subjectName){
this.subjectName = subjectName;
}
 
//getter and setter methods
public int getSubjectId() {
return subjectId;
}
public void setSubjectId(int subjectId) {
this.subjectId = subjectId;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
 
public int compareTo(String subject){      
                      if(this == null) {
                             return 1;
                      } else if(subject == null) {
                             return -1;
                      } else {
                            return this.compareTo(subject);
                      }
            }
}

Hibernate.cfg.xml

(We are developing our configuration file which instructs Hibernate on how to configure the defined classes).

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
        <property name="dialect">
           org.hibernate.dialect.OracleDialect
        </property>
        <property name="connection.url">
           jdbc:oracle:thin:@localhost:1521:XE
        </property>
        <property name="connection.username">
           system
        </property>
        <property name="connection.password">
           oracle
        </property>
        <property name="connection.driver_class">
           oracle.jdbc.driver.OracleDriver
        </property>
        <property name="hbm2ddl.auto">
           update
        </property>
        <property name="show_sql">
           true
        </property>
 
        <mapping resource="student.hbm.xml"/>
        <mapping resource="subject.hbm.xml"/>
 
    </session-factory>
 
</hibernate-configuration>

Student.hbm.xml

(We are developing our Student mapping file which instructs Hibernate on how to map the defined classes to the database tables).

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping SYSTEM
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
 
 <class name="com.w3spoint.business.Student" table="Student">
  <id name="studentId" type="int" column="Student_Id">
<generator class="native"></generator>
  </id>
 
  <property name="firstName" column="First_Name" type="string"/>
  <property name="lastName" column="Last_Name" type="string"/>
  <property name="className" column="Class" type="string"/>
  <property name="rollNo" column="RollNo" type="string"/>
  <property name="age" column="Age" type="int"/>
 
  <map name="subjects" cascade="all"  sort="natural" >
       <key column="Student_Id"/>
       <index column="Student_Class"  type=”string”/>
       <one-to-many class="com.w3spoint.business.Subject"/>
  </map>
 
 </class>
 
</hibernate-mapping>

Subject.hbm.xml

(We are developing our Subject mapping file which instructs Hibernate on how to map the defined classes to the database tables).

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping SYSTEM
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
 
  <class name="com.w3spoint.business.Subject" table="Subject">
    <id name="subjectId" type="int" column="Subject_Id">
<generator class="native"></generator>
    </id>
 
    <property name="subjectName" column="Subject_Name"
                                        type="string"></property>
 
  </class>
 
</hibernate-mapping>

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
    private static final SessionFactory sessionFactory = 
                                           buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
     SessionFactory sessionFactory = null;
        try {
         //Create the configuration object.
         Configuration configuration = new Configuration(); 
         //Initialize the configuration object 
                //with the configuration file data
         configuration.configure("hibernate.cfg.xml");
         // Get the SessionFactory object from configuration.
         sessionFactory = configuration.buildSessionFactory();
        }
        catch (Exception e) {
           e.printStackTrace();
        }
        return sessionFactory;
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    } 
}

HibernateTest.java

import java.util.HashMap;
import com.w3spoint.persistence.StudentDBOperations;
 
public class HibernateTest {
public static void main(String args[]){
TreeMap map = new TreeMap();
map.put("MCA1",new Subject("Data Structure and Algorithms"));
map.put("MCA2",new Subject("Operating Systems"));
map.put("MCA3",new Subject("DBMS"));
 
//Create the student object.
Student student = new Student("Ranbir", "Chopra", 
"BTech final", "Btech/08/65", 22);
student.setSubjects(map);
 
StudentDBOperations obj = new StudentDBOperations();
//insert student object.
obj.addStudent(student);
 
//show all student object.
obj.showAllStudentDetails();
 
}
}

StudentDBOperations.java

(This is where we will be taking the inputs for the different variables that we have).

import java.util.List;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class StudentDBOperations {
public Integer addStudent(Student student){
    Transaction tx = null;
    Integer studentId = null;
    //Get the session object.
    Session session = 
                    HibernateUtil.getSessionFactory().openSession();
    try{
        tx = session.beginTransaction();
        studentId = (Integer) session.save(student); 
        tx.commit();
      }catch (HibernateException e) {
        if(tx!=null){
         tx.rollback();
        }
        e.printStackTrace(); 
      }finally {
        session.close(); 
      }
      return studentId;
}
 
public void showAllStudentDetails(){
    Transaction tx = null;
    //Get the session object.
    Session session = 
                    HibernateUtil.getSessionFactory().openSession();
    try{
        tx = session.beginTransaction();
        List<Student> students = 
                         session.createQuery("FROM Student").list();
        for(Student student : students){
         System.out.println("First Name: " 
                                          + student.getFirstName()); 
         System.out.println("Last Name: " 
                                           + student.getLastName()); 
         System.out.println("Class: " 
                                          + student.getClassName()); 
         System.out.println("RollNo: " 
                                             + student.getRollNo()); 
         System.out.println("Age: " 
                                               + student.getAge()); 
         Map subject = student.getSubjects();
         System.out.println("Subject Name:" + 
                 ((Subject)subject.get("MCA1"))
                                                 .getSubjectName());
         System.out.println("Subject Name:" + 
                 ((Subject)subject.get("MCA2"))
                                                 .getSubjectName());
         System.out.println("Subject Name:" + 
         ((Subject)subject.get("MCA3"))
                                                 .getSubjectName());
        }
        tx.commit();
      }catch (HibernateException e) {
        if(tx!=null){
         tx.rollback();
        }
        e.printStackTrace(); 
      }finally {
        session.close(); 
      }
}
}

Output

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, Class, 
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Subject
 (Subject_Name, Subject_Id) values (?, ?)
Hibernate: insert into Subject
 (Subject_Name, Subject_Id) values (?, ?)
Hibernate: insert into Subject 
(Subject_Name, Subject_Id) values (?, ?)
Hibernate: update Subject set Student_Id=?, 
Subject_Class=? where Subject_Id=?
Hibernate: update Subject set Student_Id=?, 
Subject_Class=? where Subject_Id=?
Hibernate: update Subject set Student_Id=?, 
Subject_Class=? where Subject_Id=?
Hibernate: select student0_.Student_Id as 
Student1_0_, student0_.First_Name as First2_0_, 
student0_.Last_Name as Last3_0_, student0_.Class as 
Class0_, student0_.RollNo as RollNo0_, student0_.Age
 as Age0_ from Student student0_
First Name: Ranbir
Last Name: Chopra
Class: BTech final
RollNo: Btech/08/65
Age: 22
Hibernate: select subjects0_.Student_Id as Student3_1_, 
subjects0_.Subject_Id as Subject1_1_, subjects0_.Subject_Class 
as Subject4_1_, subjects0_.Subject_Id as Subject1_1_0_, 
subjects0_.Subject_Name as Subject2_1_0_ from Subject 
subjects0_ where subjects0_.Student_Id=?
Subject Name:Data Structure and Algorithms
Subject Name:Operating Systems
Subject Name:DBMS

Frequently Asked Questions

What distinguishes spring boot from hibernate?

While Hibernate framework is suitable for object-relational persistence, access data layers, and query retrieval services for enterprise-level applications, the Spring framework is helpful for transaction management, dependency injection, and aspect-oriented programming for applications.

What are ORM and JPA?

Java objects are changed into database tables through a technique known as object-relational mapping (ORM). In other words, this enables SQL-free interaction with a relational database. How to persist data in Java programs is specified by the Java Persistence API (JPA) specification.

What does Hibernate's lazy loading mean?

Lazy setting is used to determine whether to load child objects while loading the parent object. This setting must be made in the parent class's appropriate hibernate mapping file. True = Lazy (means not to load child) then the child objects' sluggish loading is enabled by default.

What is the use of generator class in hibernate?

When creating an ID for an item that will be used as a primary key in the database, a generator class is utilized. The persistent class's objects have an ID as a special identification. According to our needs, we can use any generator classes in our program.

What is Association in Hibernate?

One of the main components of JPA and Hibernate is association mapping. In your domain model, they represent the connection between two database tables as attributes. This lets you explore your domain model's associations, and JPQL or Criteria queries easily.

Conclusion

In this article, we have extensively discussed the Hibernate SortedMap mapping.

We hope this blog has helped you enhance your knowledge regarding Hibernate SortedMap mapping. If you want to learn more, check out our articles similar to Hibernate SortedMap mapping on Hibernate ArchitectureHibernate Configuration, and HB Generator classes.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.

Enrol in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Live masterclass