Hibernate – Bag Mapping
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
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) );
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.
Important hibernate configuration to hold the hbm file
Let us see the pojo class
Let us do the ways to store the question and choices now here
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.