Hibernate One To Many Mapping using Annotation

In this tutorial I will show how to do One to Many mapping using Hibernate Annotation. Figure 5.1 illustrates one to many relationship, via Hibernate Annotation.

Figure 5.1 Figure 5.1

According to the relationship each Employee can have any number of phone numbers. The relational model is shown below in Figure 5.2

Figure 5.2 Relational Database (one to many relationship)
Figure 5.2

1. Sql Script

Use the following Sql Script for creating table.


create table Employee(
    EMPLOYEE_ID int(10) primary key NOT NULL AUTO_INCREMENT,
    Name varchar(50));
create table Phone(
    Phone_Id int(10) primary key NOT NULL AUTO_INCREMENT,
    EMPLOYEE_ID int(10),
    Type varchar(50),
    Number varchar(50),
    Foreign Key(EMPLOYEE_ID)  References Employee(EMPLOYEE_ID));

2. Pojo

Now create Employee and Phone Class as following.

Employee.java

package com.kruders.model.bean;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.OneToMany;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
	@Id
	@GeneratedValue(strategy= GenerationType.AUTO)
	@Column(name = "EMPLOYEE_ID")
	private int employeeId;
	
	@Column(name = "Name")
	private String name;
	
	@OneToMany(mappedBy="employee")
	private Set<Phone> phone;
	public Employee() {
	}
	public Employee(String name) {
		this.name = name;
	}
	public Employee(String name, Set<Phone> phone) {
		this.name = name;
		this.phone = phone;
	}

	
	public int getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Set<Phone> getPhone() {
		return phone;
	}
	public void setPhone(Set<Phone> phone) {
		this.phone = phone;
	}
}


Phone.java

package com.kruders.model.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.JoinColumn;

@Entity
@Table(name="PHONE")
public class Phone {
	@Id
    @GeneratedValue
    @Column(name="Phone_Id")
	private long phoneId;
	
	@Column(name="Type")
	private String type;
	
	@Column(name="Number")
	private String number;
	
	@ManyToOne
    @JoinColumn(name="EMPLOYEE_ID")
	private Employee employee;
	public Phone() {
	}
	public Phone(Employee employee, long phoneId, String type, String number) {
		this.employee = employee;
		this.phoneId = phoneId;
		this.type = type;
		this.number = number;
	}
	
	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public long getPhoneId() {
		return phoneId;
	}
	public void setPhoneId(long phoneId) {
		this.phoneId = phoneId;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
}

We use @OneToMany Annotation in Employee Table and @ManyToOne Annotation in Phone Table to create the one-to-many relationship between the Employee and Phone entities.

3. Hibernate Configuration File

Now create the hibernate configuration file and add all the mapping files.

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>
	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
	<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password"></property>
	<property name="connection.pool_size">1</property>
	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
	<property name="show_sql">true</property>
	<mapping class="com.kruders.model.bean.Employee" />
	<mapping class="com.kruders.model.bean.Phone" />
</session-factory>
</hibernate-configuration>

4. Hibernate Utility Class

Now create HibernateUtil class. The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.

package com.kruders.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
  
public class HibernateUtil {
  
    private static final SessionFactory sessionFactory = buildSessionFactory();
  
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
  
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

5. Run Program

Create Main.java class that perform CRUD operations and run it as Java Application

package com.kruders.core;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.kruders.model.bean.Employee;
import com.kruders.model.bean.Phone;
import com.kruders.util.HibernateUtil;

public class Main {
	public static void main(String args[]) {
		Session session = HibernateUtil.getSessionFactory().openSession();
	    Transaction transaction = null;
		try {
			
			transaction = session.beginTransaction();
			Employee employee = new Employee("Raghav");
			session.save(employee);
			
			Phone phone = new Phone();
			phone.setType("Office");
			phone.setNumber("1234567890");
			phone.setEmployee(employee);
			session.save(phone);
			
			transaction.commit();
		}catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		//listEmployee();
		//updateEmployee("Raghav", "1234567890", "0123456789");
		//deleteEmployee("Raghav", "0123456789");
	}
	
	public void listEmployee() {
		Session session = HibernateUtil.getSessionFactory().openSession();
	    Transaction transaction = null;
		try {
			
			transaction = session.beginTransaction();
			List employees = session.createQuery("from Employee").list();
			for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
				Employee employee = (Employee) iterator.next();
				System.out.println("Name " + employee.getName());
				for(Phone phone : employee.getPhone()) {
					System.out.println("Type " + phone.getType());
					System.out.println("Number " + phone.getNumber());
				}
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	public void updateEmployee(String oldName, String oldNumber, String newNumber) {
		Session session = HibernateUtil.getSessionFactory().openSession();
	    Transaction transaction = null;
		try {
			
			transaction = session.beginTransaction();
			List employees = session.createQuery("from Employee where Name ='" + oldName + "'").list();
			for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
				Employee employee = (Employee) iterator.next();
				for(Phone phone : employee.getPhone()) {
					if(phone.getNumber().equals(oldNumber)) {
						phone.setNumber(newNumber);
					}
				}
				
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	public void deleteEmployee(String name, String number) {
		Session session = HibernateUtil.getSessionFactory().openSession();
	    Transaction transaction = null;
		try {
			
			transaction = session.beginTransaction();
			List employees = session.createQuery("from Employee where Name ='" + name + "'").list();
			for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
				Employee employee = (Employee) iterator.next();
				for(Phone phone : employee.getPhone()) {
					if(phone.getNumber().equals(number)) {
						System.out.println("Number " + phone.getNumber());
						session.delete(phone);
					} else {
						System.out.println("Number1 " + phone.getNumber());
					}
				}
			}
			
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}

The folder structure of the example is shown below in Figure 5.3

Figure 5.3 Figure 5.3

You can download the source code of this example here.

3 Responses to Hibernate One To Many Mapping using Annotation

  1. CherryCharan April 17, 2013 at 5:30 am #

    Hi I appreciate your effort in preparing these examples. Thanks

    I am designing a hospital management system where I have the following entities and tables
    1. Doctor
    2. Specialization
    The Specialization table contains master data.
    One doctor can be specialized in many, so I have a @OneToMany association of Specialization in Doctor entity, it is a unidirectional association and Specialization will not contain Doctor entity
    So for mapping doctor to specializations I have created third table doctor_specializations.
    In case I want to delete a specialization from database how should I do
    1. First delete all the rows from the table doctor_specializations and finally delete in the table specialization.
    2. Is there any way that removes all the associated rows from database when I just remove a row in specialization.
    Also suggest the better designing for the above if it is not good.

    • admin April 17, 2013 at 6:17 am #

      Your table looks like following tables:

      create table doctor(
      id int(5) primary key NOT NULL AUTO_INCREMENT,
      name varchar(20));

      create table specialization(
      id int(5) primary key NOT NULL AUTO_INCREMENT,
      specialization varchar(20));

      create table doctor_specialization(
      doctorid int(5),
      specializationid int(5),
      Primary Key(doctorid,specializationid),
      Foreign Key(doctorid) References doctor(id) ON DELETE CASCADE,
      Foreign Key(specializationid) References specialization(id) ON DELETE CASCADE);

      In this case there is many to many relationship since 1 doctor can have many specialization and 1 specialization can be assigned to many doctor.

      • CherryCharan April 18, 2013 at 11:37 am #

        Hi,

        Thanks for your reply and the suggestion. I will try with the idea.

        I have gone through your ManyToMany Annotaion article, it is helpful for me.

        I have a question here..

        In case of ManyToMany example while deleting an employee does this is cascaded to the table employee_department and the associated row of an employee is deleted from there…? If so how hibernate detects this…?

        Could you please also add the code for deleting the department which will automatically deletes the rows in employee_department table.

        Once again thanks for the response and providing a good article on hibernate.

Leave a Reply