Hibernate – one-to-many relationship example

hibernate_logo
Well, one-to-many is the type of relationship in Hibernate. This is parent child relationship where one parent can have many child. Here, you have to establishe relationship between two different entity/domain model class.

For your dependency library you can dwonload source code of hello world hibernate program, at the end of this post you can find link to download source code.

1. What is one-to-many Relationship

In one to many relateionship, one parent can have multiple childs. when you read the relationship read from parent to child. In this post, tried to demonstrate one department can have multiple employee. so in Departement table has one foreign key which hold primary key of employee. So when you select department by you can get many employee.

This can be achieved by two different ways:

  1. one by foriegn key and
  2. another way by mapping table.

In this post, tried to demonstrate by foriegn key. However, you can try with mapping table between two entities.

2. POJO/domain model class

Here, Department can have many Employee and in POJO Department object holds many reference of employee.

File: Department.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.mysoftkey.relationship.one2many;
 
import java.util.HashSet;
import java.util.Set;
 
public class Department {
 
	private Long departmentId;
	private String departmentName;
	private Set<Employee> employees;
 
	// utility method to add employee in department 
	public void addEmployee(Employee e){
	  if (employees == null){
	    employees = new HashSet<Employee>();
	  }
	}
 
   //Gernerate setter/getter , omited to clear the code
}

File: Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.mysoftkey.relationship.one2many;
 
import java.sql.Date;
 
public class Employee {
 
	private Long employeeId;
	private String firstname;
	private String lastname;
	private Date birthDate;
	private String cellphone;
	private Department department;
 
	public Employee() {
	}
 
	public Employee(String firstname, String lastname, Date birthdate,
			String phone) {
	 this.firstname = firstname;
	 this.lastname = lastname;
	 this.birthDate = birthdate;
	 this.cellphone = phone;
	}
 
	public Employee(String firstname, String lastname, String phone) {
	 this.firstname = firstname;
	 this.lastname = lastname;
	 this.cellphone = phone;
	}
 
	@Override
	public boolean equals(Object emp) {
	  if(emp instanceof Employee) {
	     Employee employee = (Employee)emp;
 
	     if(this.firstname.equals(employee.getFirstname()) &&
		this.lastname.equals(employee.getLastname()))
		return true;
	     }
 
	 return false;
	}
	@Override
	public int hashCode() {
	  return this.firstname.hashCode() + this.lastname.hashCode();
	}
 
	//Gernerate setter/getter , omited to clear the code	
}

3. .hbm.xml mapping for one-to-many relationship

File: Department.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping auto-import="false"	package="com.mysoftkey.relationship.one2many">
 
  <class name="Department" table="DEPARTMENT_one2many">
	<id name="departmentId" type="java.lang.Long" column="DEPARTMENT_ID">
		<generator class="native" />
	</id>
 
	<property name="departmentName" column="DEPT_NAME" />
 
	<set name="employees" table="employee" inverse="true" lazy="true" fetch="select">
		<key>
			<column name="department_id" not-null="true" />
		</key>
		<one-to-many class="Employee" />
	</set>
 
 </class>
</hibernate-mapping>

File: Employee.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping auto-import="false" package="com.mysoftkey.relationship.one2many">
 
  <class name="Employee" table="EMPLOYEE_one2many">
	<id name="employeeId" column="EMPLOYEE_ID">
		<generator class="native" />
	</id>
 
	<property name="firstname" />
	<property name="lastname" column="lastname" />
	<property name="birthDate" type="date" column="birth_date" />
	<property name="cellphone" column="cell_phone" />
 
        <many-to-one name="department" class="Department" fetch="select">
      <column name="department_id" not-null="true" />
    </many-to-one>
 
  </class>
</hibernate-mapping>

If you look first Department.hbm.xml, its one to many relatioship . if you look Employee.hbm.xml first , then you find many to one because many employee can have in one department.

4. Hibernate Configuration for one to many relationship

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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>
   <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_example</property>
   <property name="hibernate.connection.username">root</property>
   <property name="connection.password">root</property>
   <property name="connection.pool_size">2</property>
   <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
   <property name="show_sql">true</property>
   <property name="hbm2ddl.auto">create</property>
 
    <!-- One2Many set example and for HQL and SQL and Criteria Query as well -->
    <mapping resource="com/mysoftkey/relationship/one2many/Employee.hbm.xml"/>
    <mapping resource="com/mysoftkey/relationship/one2many/Department.hbm.xml"/>
 
  </session-factory>
</hibernate-configuration>

5. Run one to many relationship

File: OneToManyClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.mysoftkey.relationship.one2many;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
/**
 * This example is used to demonstrate one to many example in Hibenate.
 * 
 * @author Ranjeet Jha
 *
 */
public class OneToManyClient {
 
  public static void main(String[] args) {
    // in project use commented code but in demo you can use any one.
    // SessionFactory sf = HibernateUtil.getSessionFactory();
    SessionFactory sf = new Configuration().configure().buildSessionFactory();
    Session session = sf.openSession();
    session.beginTransaction();
 
    // Create Department object and populate values
    Department department = new Department();
    department.setDepartmentName("Sales");
 
    // save department 
    session.save(department);
 
    // Create list of employee object and assigned department
    Employee emp1 = new Employee("Ranjeet", "Kumar", "111");
    Employee emp2 = new Employee("Tanisha Jha", "Jha", "222");
 
    // assigned saved department to employee to add foreing key in employee table.
    emp1.setDepartment(department);
    emp2.setDepartment(department);
 
    session.save(emp1);
    session.save(emp2);
 
    session.getTransaction().commit();
    session.close();
  }
}

6. Output of one to many Hibernate relationship

Eclipse console output:

1
2
3
Hibernate: insert into DEPARTMENT_one2many (DEPT_NAME) values (?)
Hibernate: insert into EMPLOYEE_one2many (firstname, lastname, birth_date, cell_phone, department_id) values (?, ?, ?, ?, ?)
Hibernate: insert into EMPLOYEE_one2many (firstname, lastname, birth_date, cell_phone, department_id) values (?, ?, ?, ?, ?)

mySQL output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
mysql> select * from employee_one2many
    -> ;
+-------------+-------------+----------+------------+------------+---------------+
| EMPLOYEE_ID | firstname   | lastname | birth_date | cell_phone | department_id |
+-------------+-------------+----------+------------+------------+---------------+
|           1 | Ranjeet     | Kumar    | NULL       | 111        |             1 |
|           2 | Tanisha Jha | Jha      | NULL       | 222        |             1 |
+-------------+-------------+----------+------------+------------+---------------+
2 rows in set (0.00 sec)
 
mysql> select * from department_one2many;
+---------------+-----------+
| DEPARTMENT_ID | DEPT_NAME |
+---------------+-----------+
|             1 | Sales     |
+---------------+-----------+
1 row in set (0.00 sec)
 
mysql>

Your comments are welcome to improve this one-to-many relationship in Hibernate post. Happy Learning :)

Please follow and like us:
RSS
Follow by Email
Facebook
LinkedIn
Google+

Leave a Reply

Your email address will not be published. Required fields are marked *