Hibernate Collection Mapping

In this tutorial you will learn about the collection mapping in Hibernate.

Hibernate Collection Mapping

Hibernate Collection Mapping

In this tutorial you will learn about the collection mapping in Hibernate.

Hibernate provides the facility to persist the collections. A collection can be a list, set, map, collection, sorted set, sorted map. java.util.List, java.util.Set, java.util.Collection, java.util.SortedSet, java.util.SortedMap etc. are the real interface types to declared the persistent collection-value fields. Hibernate injects the persistent collections based on the type of interface. The collection instances usually behave likes the types of value behavior. Instances of collections are auto persisted if a persistent object refers it and are deleted automatically if it is not referred through. Elements of collection may shift from one table to another when a persistent object passed the collection to another persistent object.

Example :

Here the example is given below will demonstrate you how to stored elements of collection in Hibernate. To create an example I am using List. A list stores the elements with their index so index is need to be mapped with <list></list> element in .hbm.xml file. Here I have created two POJO / Persistent classes to persist the objects. Then created mapping files to map class objects with their respective tables. Next Created a hibernate configuration using which Hibernate creates a connection pool and the required environment set up. In this example a list of employee will be stored according the the address id and a list of employee can also be fetched by address id.

Table address

CREATE TABLE `address` ( 
`address_id` bigint(20) NOT NULL, 
`street` varchar(50) default NULL, 
`city` varchar(50) default NULL, 
`state` varchar(50) default NULL, 
`country` varchar(50) default NULL, 
PRIMARY KEY (`address_id`) 
)

Table employee

CREATE TABLE `employee` ( 
`employee_id` bigint(10) NOT NULL, 
`firstname` varchar(50) default NULL, 
`lastname` varchar(50) default NULL, 
`cell_phone` varchar(15) default NULL, 
`address_id` bigint(20) default NULL, 
`indx` int(11) default NULL, 
PRIMARY KEY (`employee_id`), 
KEY `FK_employee` (`address_id`), 
CONSTRAINT `FK_employee` FOREIGN KEY (`address_id`) REFERENCES `address` (`address_id`) 
)

Address.java

package 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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">
<class name="Address" table="address">
<id name="addressId" column="address_id">
<generator class="assigned" />
</id>
<property name="street" column="street"/>
<property name="city" column="city"/>
<property name="state" column="state"/>
<property name="country" column="country"/>
<list name="employees" table="employee"
inverse="false" cascade="all">
<key>
<column name="address_id" not-null="true" />
</key>
<list-index column="indx" />
<one-to-many class="roseindia.Employee" />
</list>
</class>
</hibernate-mapping>

Employee.java

package 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(Long employeeId, String firstname, String lastname, String phone) {
this.employeeId = employeeId;
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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">

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

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

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

</class>
</hibernate-mapping>

hibernate.cfg.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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.13:3306/data</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>

</session-factory>
</hibernate-configuration>

HibernateCollectionMappingExample.java

package roseindia;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;

import org.hibernate.Query;
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 HibernateCollectionMappingExample {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration().addResource("roseindia/Address.hbm.xml").addResource("roseindia/Employee.hbm.xml");
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("Hibernate Collection Mapping Example Using XML ");
Session session = sf.openSession();
session.beginTransaction();

//Address to Employee mapping
System.out.println("**********Hibernate Collection Mapping Example using Xml************");
Address address = new Address();
address.setAddressId((long) 101);
address.setStreet("West Bank");
address.setCity("New Delhi");
address.setState("Delhi");
address.setCountry("India");

Address address1 = new Address();
address1.setAddressId((long) 102);
address1.setStreet("North Bank");
address1.setCity("DumDum");
address1.setState("West Bengal");
address1.setCountry("India");

Employee e1 = new Employee((long)2001, "Romesh", "Thapar", "9999999999");
Employee e2 = new Employee((long)2002, "Smita", "Khanna", "3333333333");

Employee e3 = new Employee((long)2003,"Somesh","Dutta", "9245163801" );
Employee e4 = new Employee((long)2004,"Rajeev", "singh","0125784560");

address.setEmployees(new ArrayList<Employee>());
address.getEmployees().add(e1);
address.getEmployees().add(e2);

address1.setEmployees(new ArrayList<Employee>());
address1.getEmployees().add(e3);
address1.getEmployees().add(e4);

session.save(address);
session.save(address1);
session.getTransaction().commit();
session.close();
session = sf.openSession();
System.out.println("Enter Address Id");
Scanner scan = new Scanner(System.in);
String addId = scan.nextLine();
Query query = session.createQuery("select e.employeeId, e.firstname, e.lastname, e.cellphone from Employee e where address_id ="+addId);
Iterator emp = query.iterate();
System.out.println("EmployeeId \t FirstName \t LastName \t CellPhone");
while(emp.hasNext())
{
Object[] obj = (Object[]) emp.next();
System.out.println(obj[0]+" \t \t"+ obj[1]+ " \t \t"+ obj[2]+ " \t\t " + obj[3]);

}
}
}

Output :

When you will execute the HibernateCollectionExample.java file (RightClick -> RunAs -> Java Application) you will see the data are stored in the table as follows :

1. employee table

2. address table

And on console you will see the query execution as follows :

Hibernate Collection Mapping Example Using XML 
**********Hibernate Collection Mapping Example using Xml************
Hibernate: select employee_.employee_id, employee_.firstname as firstname1_, employee_.lastname as lastname1_, employee_.cell_phone as cell4_1_, employee_.address_id as address5_1_ from employee employee_ where employee_.employee_id=?
Hibernate: select employee_.employee_id, employee_.firstname as firstname1_, employee_.lastname as lastname1_, employee_.cell_phone as cell4_1_, employee_.address_id as address5_1_ from employee employee_ where employee_.employee_id=?
Hibernate: select employee_.employee_id, employee_.firstname as firstname1_, employee_.lastname as lastname1_, employee_.cell_phone as cell4_1_, employee_.address_id as address5_1_ from employee employee_ where employee_.employee_id=?
Hibernate: select employee_.employee_id, employee_.firstname as firstname1_, employee_.lastname as lastname1_, employee_.cell_phone as cell4_1_, employee_.address_id as address5_1_ from employee employee_ where employee_.employee_id=?
Hibernate: insert into address (street, city, state, country, address_id) values (?, ?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id, employee_id) values (?, ?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id, employee_id) values (?, ?, ?, ?, ?)
Hibernate: insert into address (street, city, state, country, address_id) values (?, ?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id, employee_id) values (?, ?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id, employee_id) values (?, ?, ?, ?, ?)
Hibernate: update employee set address_id=?, indx=? where employee_id=?
Hibernate: update employee set address_id=?, indx=? where employee_id=?
Hibernate: update employee set address_id=?, indx=? where employee_id=?
Hibernate: update employee set address_id=?, indx=? where employee_id=?

And when you will give the address id (available in address table) on asking an output will be as follows :

Download Source Code