Home Hibernate Hibernaterelationships Hibernate One-to-one Relationships

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate One-to-one Relationships

Advertisement
This section we will see the the structure of Entity classes and the one-to-one mapping tags in the .hbm.xml file.

Hibernate One-to-one Relationships

     

Hibernate One-to-one Relationships - One to one relationships example using xml meta-data

This section we will see the the structure of Entity classes and the one-to-one mapping tags in the .hbm.xml file. We will also run the example and see the data into database.

One-to-One Relationships

In case of one-to-one relationships, each row in table A linked to only one row in table B. Here we will implement one-to-one relationship between two entries Employee and EmployeeAddress.

We are using two tables employee and employee_address and java entities Employee and EmployeeAddress maps respectively. Here is the ER diagram

Java Persistence Objects:

The code for Employee.java is given below:

package roseindia;

public class Employee {

  private int id;
  private String name;
  private EmployeeAddress address;
  public int getId() {
  return id;
  }
  public void setId(int id) {
  this.id = id;
  }
  public String getName() {
  return name;
  }
  public void setName(String name) {
  this.name = name;
  }
  public EmployeeAddress getAddress() {
  address.setEmpid(getId());
  return address;
  }
  public void setAddress(EmployeeAddress address) {
  this.address = address;
  }
  
}

The code for EmployeeAddress.java is given below:

package roseindia;

public class EmployeeAddress {
  private int id;
  private int empid;
  private String address;
  private String country;
  public int getId() {
  return id;
  }
  public void setId(int id) {
  this.id = id;
  }
  public int getEmpid() {
  return empid;
  }
  public void setEmpid(int empid) {
  this.empid = empid;
  }
  public String getAddress() {
  return address;
  }
  public void setAddress(String address) {
  this.address = address;
  }
  public String getCountry() {
  return country;
  }
  public void setCountry(String country) {
  this.country = country;
  }
}

Mapping xml file (Employee.hbm.xml):

This file contains the mapping for both the entities Employee and EmployeeAddress.

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="roseindia.Employee" table="employee">

<id name="id" type="int" column="employee_id" >

<generator class="native"/>

</id>

<property

name="name"

type="java.lang.String"

column="employee_name"

not-null="true"

length="50"

/>

<one-to-one name="address" class="roseindia.EmployeeAddress" property-ref="empid"

cascade="all"/>

</class>

??

<class name="roseindia.EmployeeAddress" table="employee_address">

<id name="id" type="int" column="id" >

<generator class="native"/>

</id>

<property

name="address"

type="java.lang.String"

column="address"

not-null="true"

length="255"

/>

<property

name="country"

type="java.lang.String"

column="country"

not-null="true"

length="100"

/>

<property

name="empid"

type="int"

column="emp_id"

not-null="true"

length="100"

/>

</class>

??

??

</hibernate-mapping>

The following mapping tag defines the one-to-one mapping between Employee and EmployeeAddress entities.

<one-to-one name="address" class="roseindia.EmployeeAddress" property-ref="empid" cascade="all"/>

Here empid variable is defined in EmployeeAddress entity which is used for defining the relationships.

Running the Program:

To run and test the program you have to execute the OneToOneRelation.java. Here is the full code of OneToOneRelation.java file:

package roseindia;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class OneToOneRelation {
  public static void main(String[] args) {
  SessionFactory sessFact=null;
  Session sess=null;
  try{
  sessFact=new Configuration().configure().buildSessionFactory();
  sess=sessFact.openSession();
  System.out.println("sess:"+sess);   
  //Create Customer Object
  Employee emp = new Employee();  
  emp.setName("Deepak");   
  //Create address object
  EmployeeAddress address = new EmployeeAddress();
  //Set some values
  address.setAddress("Delhi");
  address.setCountry("India");   
  emp.setAddress(address);   
  Transaction tr = sess.beginTransaction();
  sess.save(emp);
  tr.commit();   
  System.out.println("Done");
  }
  catch (HibernateException he){
  System.out.println(he.getMessage());
  }
  finally{
  //SessionFactory close 
  sessFact.close();
  //Session close
  sess.close();
  }   } }

The above code is self explanatory, we are creating the objects of Employee and EmployeeAddress and filling the values. Then we are setting the address object into Employee object and finally calling the sess.save(emp) method. On calling the save() method on the Session object, hibernate reads the state of the objects and persists the data into database.

You can run the example in eclipse and you should get the following output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

sess:SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])

Hibernate: insert into employee (employee_name) values (?)

Hibernate: insert into employee_address (address, country, emp_id) values (?, ?, ?)

Done

In this section we learned about the one-to-one relationships in Hibernate.

In next section we will learn how to create and run the one-to-many mapping in Hibernate.

Download the code example

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 28, 2010

Related Tutorials

Discuss: Hibernate One-to-one Relationships  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com