Skip to content
Related Articles
Open in App
Not now

Related Articles

Hibernate – Bag Mapping

Improve Article
Save Article
  • Last Updated : 10 Jun, 2022
Improve Article
Save Article

For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of “HAS A” relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, we can implement that. Let us see that

 

Example Project

Let us create MYSQL tables first

--Main table where each question is identified by qId and it is unique
create table Questions(
    qId int auto_increment,
    questionName varchar(50),
    Primary key (qId)
);
--For each question, we will have several choices. It is denoted as below
create table Choices(
  questionId int,
  answer varchar(100)
  );

Project Structure:

Project Structure

 

In mapping file, we have to represent the table relationship via a bag name. It is like one to many relationship only but via bag name we are representing that.

multiplechoicequestion.hbm.xml

XML




<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
<hibernate-mapping>  
         
   <!-- Questions is the table name -->
   <class name="com.gfg.hibernate.pojo.MultipleChoiceQuestion" table="Questions">  
     <id name="qId">  
       <generator class="increment"></generator>  
     </id>  
       
     <property name="questionName"></property>  
        
     <!--  This is almost like a list but here we are using bag instead of a list
              i.e. 1 question can have n choices. It is done by means of bag.
              Main advantage is it does not have a index element -->
     <bag name="choices" table="Choices">  
       <key column="questionId"></key>  
       <element column="answer" type="string"></element>  
     </bag>  
  
   </class>  
              
</hibernate-mapping>


Important hibernate configuration to hold the hbm file

hibernate.cfg.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
                        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        
        <!--  As we are connecting mysql, those driver classes, database name, 
              username and password are specified
              Please change the information as per your requirement -->
        <property name="hbm2ddl.auto">update</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/geeksforgeeks?serverTimezone=UTC</property>        
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
          
          <!--  Used bag mapping instead of list and it is specified here -->
        <mapping resource="multiplechoicequestion.hbm.xml" /> 
        
    </session-factory>
</hibernate-configuration>


Let us see the pojo class 

MultipleChoiceQuestion.java

Java




import java.util.List;
public class MultipleChoiceQuestion {
  
    // Attributes should match
    // with 'Questions' table
    private int qId;
    private String questionName;
  
    // As each question may have 1 - N choices,
    // let us collect via a list here
    private List<String> choices;
  
    public int getqId() { return qId; }
    public void setqId(int qId) { this.qId = qId; }
    public String getQuestionName() { return questionName; }
    public void setQuestionName(String questionName)
    {
        this.questionName = questionName;
    }
    public List<String> getChoices() { return choices; }
    public void setChoices(List<String> choices)
    {
        this.choices = choices;
    }
}


Let us do the ways to store the question and choices now here

QuestionRepository.java

Java




import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
  
import com.gfg.hibernate.pojo.MultipleChoiceQuestion;
  
public class QuestionRepository {
    public static void main(String[] args)
    {
  
        StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(standardServiceRegistry).getMetadataBuilder().build();
  
        SessionFactory sessionFactory = meta.buildSessionFactory();
        Session session = sessionFactory.openSession();
  
        Transaction transaction = session.beginTransaction();
  
        ArrayList<String> answerList1 = new ArrayList<String>();
        answerList1.add("Object Oriented Programming language");
        answerList1.add("Structural Programming language");
        answerList1.add("Hybrid Programming language");
        answerList1.add("Monolithic Programming language");
  
        ArrayList<String> answerList2 = new ArrayList<String>();
        answerList2.add("User friendly Object oriented language");
        answerList2.add("Complicated structural language");
        answerList2.add("Functional language");
        answerList2.add("RDBMS");
  
        MultipleChoiceQuestion mcq1 = new MultipleChoiceQuestion();
        mcq1.setQuestionName("Java is");
        mcq1.setChoices(answerList1);
  
        MultipleChoiceQuestion mcq2 = new MultipleChoiceQuestion();
        mcq2.setQuestionName("Python is");
        mcq2.setChoices(answerList2);
  
        session.persist(mcq1);
        session.persist(mcq2);
  
        transaction.commit();
        session.close();
        System.out.println("success. We have seen bag mapping here. Check the db data");
    }
}


Execution of the project and output

 

As we have followed bag mapping, when the program runs it has inserted the respective records in both the tables Let us see them. 

 

Its respective choices can be seen as follows

 

From the inserted data, we can come to a conclusion that Bag mapping helps to insert data as one to many concept. Instead of list, using bag mapping, relationship is happening. In this tutorial, we have seen the concept of bag mapping.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!