Hibernate One to many XML Mapping bag example

In this section, you will learn how to use bag element instead of or element in mapping XML file in Hibernate.



How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code

Hibernate One to many XML Mapping <bag> example

In this section, you will learn how to use <bag> element instead of <set> or <list> element in mapping XML file in Hibernate.


Table Mapping

In the below figure , the address_id is the foreign key to the table employee. With the help of address_id , we are here doing one to many mapping. The logic behind using this mapping in below example is - many employees can have the same street, city, state ,country as address. Only the house number differentiate the two people addresses. So address_id in employee table can have many same address ids which indicates to the same address in the address table.

In this example, we are inserting data into two table simultaneously which are correlated to each other. Here address table holding the data of the unique addresses, each having an unique id. This unique id is used to connect the address to the employee table's address id. This indicates the address of the employee. In conclusion, many employee can have the same address (except house/flat numbers). For example : Two people may have address- Salt Lake, Kolkata, West Bengal, India.

The project hierarchy and jar file used is given below :


hibernate.cfg.xml( /src/hibernate.cfg.xml )

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property>


Address.java( /src/net/roseindia/Address.java )

package net.roseindia;

import java.util.List;

public class Address {

private Long addressId;

private String street;

private String city;

private String state;

private String country;

private List<Employee> employees;

public Long getAddressId() {
return addressId;

public void setAddressId(Long addressId) {
this.addressId = addressId;

public String getStreet() {
return street;

public void setStreet(String street) {
this.street = street;

public String getCity() {
return city;

public void setCity(String city) {
this.city = city;

public String getState() {
return state;

public void setState(String state) {
this.state = state;

public String getCountry() {
return country;

public void setCountry(String country) {
this.country = country;

public List<Employee> getEmployees() {
return employees;

public void setEmployees(List<Employee> employees) {
this.employees = employees;


Address.hbm.xml( /src/net/roseindia/Address.hbm.xml )

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping package="net.roseindia">
<class name="Address" table="address">
<id name="addressId" column="address_id">
<generator class="native" />
<property name="street" column="street"/>
<property name="city" column="city"/>
<property name="state" column="state"/>
<property name="country" column="country"/>
<bag name="employees" table="employee"
inverse="true" lazy="true" fetch="select">
<column name="address_id" not-null="true" />
<one-to-many class="net.roseindia.Employee" />

Employee.java( /src/net/roseindia/Employee.java )

package net.roseindia;

public class Employee {
private Long employeeId;

private String firstname;

private String lastname;

private String cellphone;

private Address address;

public Address getAddress() {
return address;

public void setAddress(Address address) {
this.address = address;

public Employee() {}

public Employee(String firstname, String lastname, String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.cellphone = phone;

public Long getEmployeeId() {
return employeeId;

public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;

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 getCellphone() {
return cellphone;

public void setCellphone(String cellphone) {
this.cellphone = cellphone;


Employee.hbm.xml( /src/net/roseindia/Employee.hbm.xml )

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping package="net.roseindia">

<class name="Employee" table="employee">
<id name="employeeId" column="employee_id">
<generator class="native" />

<property name="firstname" column="firstname"/>
<property name="lastname" column="lastname" />
<property name="cellphone" column="cell_phone" />

<many-to-one name="address" class="net.roseindia.Address" fetch="select">
<column name="address_id" not-null="true" />


ManageEmployee.java( /src/net/roseindia/ManageEmployee.java )

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class ManageEmployee {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration().addResource("net/roseindia/Address.hbm.xml").addResource("net/roseindia/Employee.hbm.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
System.out.println("Hibernate One to many Mapping <bag> example");
Session session = sf.openSession();

Address address = new Address();
address.setStreet("Lake Gardens");
address.setState("West Bengal");

Employee e1 = new Employee("Rakesh", "Sharma", "9999999999");
Employee e2 = new Employee("Kapil", "Kaushal", "3333333333");





In the console, you will get the following output :

Hibernate One to many Mapping <bag> example
Hibernate: insert into address (street, city, state, country) values (?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id) values (?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id) values (?, ?, ?, ?)

In the employee table, you will get the following records :


In the address table, you will get the following record :

Download Source Code


Share on Google+Share on Google+

Hibernate One to many XML Mapping bag example

Posted on: February 27, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Hibernate One to many XML Mapping example  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image