Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create One to One mapping in Hibernate

In this article we are going to learn the process of creating one to one mapping in hibernate that would help to associate a relationship between two different database tables.

Objective:

  • To learn, what is One to One Mapping
  • To learn, How to create One to One Mapping in hibernate
  • To learn, How to define mapping column name not same as class reference variable name.

Common Mapping Terms in Hibernate:

One to One Mapping: This kind of mapping defines the relationship between two tables using one attribute of each tables like relationship between empTable and deptTable related by empId and deptId. The attribute name deptId will be referenced by using refrence variable of referencing POJO class.

One To One Mapping in Detail:

Review Example Directory Structure:

Hibernate Directory structure for OneToOne Mapping Example

Figure 1: Hibernate Directory structure for OneToOne Mapping Example

Required library jar files to run this example
Required library jar files to run this example

Figure 2: Required library jar files to run this example

In this case, we need to have two database classes, let’s name them as Employee and Department.

Hence create two POJO Classes named Employee.java and Department.java having class attributes respectively:

empId and empName for Employee class
and
deptId and deptName for Department class.

Now create getter and setter methods for these classes.

Use @Entity annotation before both of the classes, which is defined in the javax.persistance.Entity class.

@Id before getEmpId() and getDeptId() methods defined in javax.persistance.Id class.

Also define @GeneratedValue with attribute name strategy with value GenerationType_AUTO before these two methods as follows:

@Id @GeneratedValue (strategy = GenerationType_AUTO)
Public void getEmpId(){
return empId;
}
@Id @GeneratedValue (strategy = GenerationType_AUTO)
Public void getDeptId(){
return deptId;
}
@GeneratedValue is defined in javax.persistance.GeneratedValue class.

Once these POJO classes are created as entity type, it is necessary to update mapping tag for these two classes into the hibernate configuration file named hibernate.cfg.xml file.

<mapping class = "mapping.Employee"/>
	<mapping class = "mapping.Department"/>

To run and crate these classes into the database, we are required to have one more class , that is the java application class having the main method defination. This method contains hibernate connection and session management statement to handle these two class objects. This class name would be OneToOneMapping class.

This class configures hibernate.cfg.xml file using Configuration class object cfg.

	Configuration cfg = new Configuration();
	cfg.configure(“hibernate.cfg.xml");

And then create session factory object to build session factory

	SessionFactory sessionFactory = cfg.buildSession_Factory();

Once it’s done. Create a Session refernce variable and initialize it with the new opened session using session factory object.

	Session session = session.Factory_openSession();

Now crate two object for classes Employee and Department respectively.

	Employee emp = new Employee();
	Department dept = new Department();

And initialize these objects using their setter methods. Once these objects are initiaized, save these objects into the session using session.save() method.

emp.setEmpName("Emp1");
	dept.setDeptName("Dept1");
session.save(emp);
	session.save(dept);

And now commit the session transaction using session.getTransaction.commit() method.

And at last close the session using session.close() method.

 Showing Hibernate created two tables independently

Figure 3: Showing Hibernate created two tables independently

Above figure shows that two tables named employee and department were create, while run OneToOne.java file runs.

In order to One to One mapping relationship between these two table, we have to use refrence of one database table named (Department) to another table (Employee).

Department dept;

To define a One to One relationship using hibernate, annotation @OneToOne need to be place before the class refrence variable declaration or before the getter method of this refrence variable.

@OneToOne
Department dept;
Or
@OneToOne
public void getDept(){
return dept;
}

Now, we are required to call the setter method for the deparment refrence variable into the OneToOneMapping class by passing the department class object.

emp.setDept(dept);

Now, let see the effect for One to One Mapping configuration between these two tables.

Hibernate created additional attribute to Employee table named DEPT_ID using @OneToOne

Figure 4: Hibernate created additional attribute to Employee table named DEPT_ID using @OneToOne

As figure shows that hibernate created an additional attribute to Employee table named dept_id, which maps the department id of Department table to Employee table. The column name dept_id maps to deptId of Department table.

This is possilbe to rename the mapping column as user defined, not same as class variable name. This can possible by using annotation @JoinColumn and its attribute name and its value.

@JoinColumn (name = “DEPT_ID”)

This annotation is defined in the class javax.persistance.JoinColumn. Following figure shows these updates:

Hibernate @JoinColumn updates the OneToOne mapping column name

Figure 5: Hibernate @JoinColumn (name = “”) updates the OneToOne mapping column name

Example Code

Listing 1: Employee.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Employee {
	private int emp_Id;
	private String emp_Name;
	
	private Department dept;
	
	@Id
	@GeneratedValue (strategy = GenerationType_AUTO)
	public int getEmpId() {
		return emp_Id;
	}
	public void setEmpId(int empId) {
		this.empId = emp_Id;
	}
	@OneToOne
	@JoinColumn (name = "deptId")
	public Department getDept() {
		return dept;
	}
	public void setDept(Department dept) {
		this.dept = dept;
	}
	@Column 
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String emp_Name) {
		this.empName = empName;
	}
}

Listing 2: Department.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Department {
	int deptId;
	String dept_Name;
	
	@Id
	@GeneratedValue (strategy = GenerationType_AUTO)
	public int getDept_Id() {
		return dept_Id;
	}
	public void setDeptId(int dept_Id) {
		this.deptId = dept_Id;
	}
	
	@Column
	public String getDept_Name() {
		return dept_Name;
	}
	public void setDept_Name(String dept_Name) {
		this.deptName = deptName;
	}
}

Listing 3: OneToOneMapping.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class OneToOneMapping {
	public static void main(String[]args){
		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml");
		SessionFactory sessionFactory = cfg.buildSessionFactory();
		Session session = sessionFactory.open_Session();
		
		Employee emp = new Employee();
		Department deptObj = new Department();
		
		emp.setEmp_Id(2);
		emp.setEmp_Name("Emp1");
		deptObj.setDept_Id(2);
		deptObj.setDeptName("Dept1");
		
		session.begin_Transaction();
		session.save(emp);
		session.save(deptObj);
		session.getTransaction().commit();
		session.close();
		
	}
}

Listing 4: Hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-config PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.1"
          "http://hibernate.net/hibernate-config-3.1.dtd">

<!-- Generated by MyEclipseTools.                   -->
<hibernate-config>

    <session-factory>
    	<!-- Database Connection Settings -->
        <property name="connection.driver_class">com.mysql</property>
        <property name="connection.url">jdbc:mysql://localhost/demo</property>
        <property name="connection_userID">root</property>
        <property name="connection_pWD"></property>
        
        <!-- JDBC Connection Pool (Use the built-IN) -->
        <property name="connection.pool">1</property>
        
        <!-- Diable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.NoCacheProvider</property>
        
        <!-- Database Schema Modification Type -->
        <property name="hbmdl.auto">create</property>
        
        <!-- Database Dialect -->
        <property name="dialect">org.hibernate.MySQLDialect</property>
        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">1</property>
        
        <!-- Hibernate Class Mapping -->
		<mapping class = "mapping_Employee"/>
		<mapping class = "mapping_Department"/>
	</session-factory>
</hibernate-config>

Conclusion:

In this article, we learn:

  • What is One to One mapping
  • How to define One to One mapping using hibernate
  • How to define mapped column name not same as class reference variable name.


Working in Software Development domain from 7 years now and is well equipped with programming languages like HTML, CSS, Java, PHP, .NET etc.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login