Table of contents
1.
Introduction
2.
Example on Hibernate Map mapping
2.1.
Question.java
2.2.
question.hbm.xml
2.3.
hibernate.cfg.xml
2.4.
StoreTest.java
2.5.
FetchTest.java
2.6.
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 Map 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 stores elements in key-value pairs in a Java collection. No duplicate elements will be accepted. The map interface allows the mapped contents to be represented as a collection of values or a set of key-value mappings, or as a set of keys (keys alone). java.util. An unordered map can be initialized with the help of a hash map. It is indicated by the <map> element in the mapping table.

A Map is mapped with a <map> element in the mapping table and an unordered map can be initialized with java.util.HashMap.

Let us take an example and understand Hibernate Map mapping.

Example on Hibernate Map mapping

We need to create the given below pages for mapping map elements.

  1. Question.java
  2. hibernate.cfg.xml
  3. question.hbm.xml
  4. FetchTest.java
  5. StoreTest.java

Question.java

import java.util.Map;  
  
public class Question {  
private int id;  
private String name,userName;  
private Map<String,String> answer;  
  
public Question() {}  
public Question(String name, String userName, Map<String, String> answer) {  
    super();  
    this.name = name;  
    this.userName = userName;  
    this.answer = answer;  
}  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public String getUsername() {  
    return userName;  
}  
public void setUsername(String username) {  
    this.userName = userName;  
}  
public Map<String, String> getAnswers() {  
    return answer;  
}  
public void setAnswers(Map<String, String> answer) {  
    this.answers = answer;  
}  
}  

question.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
            
<hibernate-mapping>  
  
<class name="com.codingninjas.Question" table="question736">  
<id name="id">  
<generator class="native"></generator>  
</id>  
<property name="name"></property>  
<property name="username"></property>  
  
<map name="answers" table="answer736" cascade="all">  
<key column="questionid"></key>  
<index column="answer" type="string"></index>  
<element column="username" type="string"></element>  
</map>  
</class>  
  
</hibernate-mapping>   

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
  
<hibernate-configuration>  
  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
        <property name="connection.username">system</property>  
        <property name="connection.password">jtp</property>  
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
      
    <mapping resource="question.hbm.xml"/>  
    </session-factory>  
  
</hibernate-configuration> 

StoreTest.java

import java.util.HashMap;    
import org.hibernate.*;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
  
  
public class StoreTest {    
public static void main(String[] args) {    
   
    StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
    Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
      
    SessionFactory factory=meta.getSessionFactoryBuilder().build();  
    Session session=factory.openSession();  
   
Transaction t=session.beginTransaction();    
    
HashMap<String,String> map1=new HashMap<String,String>();    
map1.put("Java is a programming language","Rakesh Kumar");    
map1.put("Java is a platform","Vinod Singh");    
    
HashMap<String,String> map2=new HashMap<String,String>();    
map2.put("Servlet technology is a server side programming","Rakesh Kumar");    
map2.put("Servlet is an Interface","Vinod Singh");    
map2.put("Servlet is a package","Charlie Milton");    
    
Question question1=new Question("What is Java?","Aryan",map1);    
Question question2=new Question("What is Servlet?","Anil Kumar",map2);    
    
session.persist(question1);    
session.persist(question2);    
    
t.commit();    
session.close();    
System.out.println("successfully stored");    
}    
}

FetchTest.java

import java.util.*;    
import javax.persistence.TypedQuery;  
import org.hibernate.*;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
   
public class FetchTest {    
public static void main(String[] args) {    
    StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
    Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
      
    SessionFactory factory=meta.getSessionFactoryBuilder().build();  
    Session session=factory.openSession();    
            
 TypedQuery query=session.createQuery("from Question ");    
 List<Question> list=query.getResultList();    
            
 Iterator<Question> iterator=list.iterator();    
 while(iterator.hasNext()){    
  Question question=iterator.next();    
  System.out.println("question id:"+question.getId());    
  System.out.println("question name:"+question.getName());    
  System.out.println("question posted by:"+question.getUsername());    
  System.out.println("answers.....");    
  Map<String,String> map=question.getAnswers();    
  Set<Map.Entry<String,String>> set=map.entrySet();    
                
  Iterator<Map.Entry<String,String>> iteratoranswer=set.iterator();    
  while(iteratoranswer.hasNext()){    
   Map.Entry<String,String> entry=(Map.Entry<String,String>)iteratoranswer.next();    
   System.out.println("answer name:"+entry.getKey());    
   System.out.println("answer posted by:"+entry.getValue());    
  }    
 }    
session.close();    
}    
}

Output

question id:1
question name: What is Java?
question posted by: Aryan
answers…..
answer name: Java is a programming language
answer posted by: Rakesh Kumar
answer name: Java is a platform
answer posted by: Vinod Singh 
question id: 2
question name: What is Servlet?
question posted by: Anil Kumar
answers…..
answer name: Servlet is a package
answer posted by: Charlie Milton
answer name: Servlet technology is a server side programming
answer posted by: Rakesh Kumar
answer name: Servlet is an Interface
answer posted by: Vinod Singh

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 map 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 Map mapping.

We hope this blog has helped you enhance your knowledge regarding Hibernate Map mapping. If you want to learn more about Hibernate Map mapping, check out our articles on Hibernate ArchitectureHibernate ConfigurationHB 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