Open In App
Related Articles

Hibernate – Bag Mapping

Improve Article
Save Article
Like 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.



<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
   <!-- Questions is the table name -->
   <class name="com.gfg.hibernate.pojo.MultipleChoiceQuestion" table="Questions">  
     <id name="qId">  
       <generator class="increment"></generator>  
     <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>  

Important hibernate configuration to hold the hbm file



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
        <!--  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="">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" /> 

Let us see the pojo class


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


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");
        MultipleChoiceQuestion mcq1 = new MultipleChoiceQuestion();
        mcq1.setQuestionName("Java is");
        MultipleChoiceQuestion mcq2 = new MultipleChoiceQuestion();
        mcq2.setQuestionName("Python is");
        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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 10 Jun, 2022
Like Article
Save Article
Similar Reads
Complete Tutorials