Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate4 Hibernate One to One Bi-directional Mapping

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate One to One Bi-directional Mapping

Advertisement
In this section, you will learn one to one bi-directional mapping in Hibernate.

Hibernate One to One Bi-directional Mapping

In this section, you will learn one to one bi-directional mapping in Hibernate.

In bi-directional mapping, the parent table can be retrieved by the child table and the child table can be retrieved by the parent table. Means retrieval can be done in both direction or bi-directional. That's why we call it bi-directional mapping.

EXAMPLE

In the given below example, address table access the employee table to insert the record. Due to bi-directional nature, employee table can also insert the records in both the tables.

The project hierarchy and the jar file used in the project is given below:

The SQL query used to create the worker table is given below :

CREATE TABLE `worker` ( 
`worker_id` bigint(10) NOT NULL auto_increment, 
`firstname` varchar(50) default NULL, 
`lastname` varchar(50) default NULL, 
`birth_date` date NOT NULL, 
`cell_phone` varchar(15) NOT NULL, 
PRIMARY KEY (`worker_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

The SQL query used to create the workerdetail table is given below :

CREATE TABLE `workerdetail` ( 
`worker_id` bigint(20) NOT NULL auto_increment, 
`street` varchar(50) default NULL, 
`city` varchar(50) default NULL, 
`state` varchar(50) default NULL, 
`country` varchar(50) default NULL, 
PRIMARY KEY (`worker_id`), 
CONSTRAINT `FK_workerdetail` FOREIGN KEY (`worker_id`) REFERENCES `worker` (`worker_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1

CODE

hibernate.cfg.xml ( /src/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/anky</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>

<mapping class="net.roseindia.WorkerDetail"/>
<mapping class="net.roseindia.Worker"/>

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

Worker.java( /src/net/roseindia/Worker.java )

package net.roseindia;

import java.util.Date;

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

@Entity
@Table(name = "worker")
public class Worker {

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name = "worker_id")
private Long workerId;



@Column(name = "firstname")
private String firstname;

@Column(name = "lastname")
private String lastname;

@Column(name = "birth_date")
private Date birthDate;

@Column(name = "cell_phone")
private String cellphone;

@OneToOne(mappedBy = "worker", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name="worker_id")
private WorkerDetail workerDetail;

public Worker() {

}

public Worker(String firstname, String lastname, Date birthdate,
String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.birthDate = birthdate;
this.cellphone = phone;

}

public Long getWorkerId() {
return workerId;
}

public void setWorkerId(Long workerId) {
this.workerId = workerId;
}

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 Date getBirthDate() {
return birthDate;
}

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

public String getCellphone() {
return cellphone;
}

public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}

public WorkerDetail getWorkerDetail() {
return workerDetail;
}

public void setWorkerDetail(WorkerDetail workerDetail) {
this.workerDetail = workerDetail;
}
}

WorkerDetail.java( /src/net/roseindia/WorkerDetail.java  )

package net.roseindia;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name="workerdetail")
public class WorkerDetail {
@Id
@Column(name="worker_id", unique=true, nullable=false)
@GeneratedValue(generator="gen")
@GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="worker"))
private Long workerId;

@Column(name="street")
private String street;

@Column(name="city")
private String city;

@Column(name="state")
private String state;

@Column(name="country")
private String country;

@OneToOne(fetch = FetchType.LAZY, optional=true)
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@PrimaryKeyJoinColumn
private Worker worker;

public WorkerDetail() {

}

public WorkerDetail(String street, String city, String state, String country) {
this.street = street;
this.city = city;
this.state = state;
this.country = country;
}

public Long getWorkerId() {
return workerId;
}

public void setWorkerId(Long workerId) {
this.workerId = workerId;
}

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 Worker getWorker() {
return worker;
}

public void setWorker(Worker worker) {
this.worker = worker;
}
}

ManageWorker.java( /src/net/roseindia/ManageWorker.java )

package net.roseindia;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

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 ManageWorker {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

@SuppressWarnings("unchecked")
public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
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("Example : Hibernate One to One Mapping using Annotation ");
Session session = sf.openSession();
session.beginTransaction();

///////////worker to workerdetail mapping//////////////
System.out.println("-----------------worker to workerdetail mapping-----------------");
WorkerDetail workerDetail = new WorkerDetail("Lake Town", "Kolkata",
"West Bengal", "India");

//For passing Date of birth as String
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dob=null;
try {
dob = sdf.parse("1987-05-21");
} catch (ParseException e) {
e.printStackTrace();
}

Worker worker = new Worker("Sushmita", "Dasgupta",dob,
"919595959595");
worker.setWorkerDetail(workerDetail);
workerDetail.setWorker(worker);

session.save(worker);

///////////////workerdetail to worker mapping//////////
System.out.println("-----------------workerdetail to worker mapping-----------------");
//For passing Date of birth as String
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date dob2=null;
try {
dob2 = sdf2.parse("1987-06-30");
} catch (ParseException e) {
e.printStackTrace();
}
Worker worker2 = new Worker("Nayana", "Ahuja",dob2,"919191919191");
WorkerDetail workerDetail2 = new WorkerDetail("Prince Edward Street", "Lucknow","Uttar Pradesh", "India");
worker2.setWorkerDetail(workerDetail2);
workerDetail2.setWorker(worker2);

session.save(workerDetail2);

session.getTransaction().commit();

System.out.println("------------------Showing List of worker-----------------------");
List<Worker> workerList = session.createQuery("from Worker").list();
for (Worker work1 : workerList) {
System.out.println(work1.getFirstname() + " , "
+ work1.getLastname() + ", "
+ work1.getWorkerDetail().getState());
}
session.close();

}
}

OUTPUT

After the above code execution, you can see the following lines in console :

Example : Hibernate One to One Mapping using Annotation 
-----------------worker to workerdetail mapping-----------------
Hibernate: insert into worker (birth_date, cell_phone, firstname, lastname) values (?, ?, ?, ?)
-----------------workerdetail to worker mapping-----------------
Hibernate: insert into workerdetail (city, country, state, street, worker_id) values (?, ?, ?, ?, ?)
Hibernate: insert into worker (birth_date, cell_phone, firstname, lastname) values (?, ?, ?, ?)
Hibernate: insert into workerdetail (city, country, state, street, worker_id) values (?, ?, ?, ?, ?)
------------------Showing List of worker-----------------------
Hibernate: select worker0_.worker_id as worker1_1_, worker0_.birth_date as birth2_1_, worker0_.cell_phone as cell3_1_, worker0_.firstname as firstname1_, worker0_.lastname as lastname1_ from worker worker0_
Hibernate: select workerdeta0_.worker_id as worker1_0_0_, workerdeta0_.city as city0_0_, workerdeta0_.country as country0_0_, workerdeta0_.state as state0_0_, workerdeta0_.street as street0_0_ from workerdetail workerdeta0_ where workerdeta0_.worker_id=?
Hibernate: select workerdeta0_.worker_id as worker1_0_0_, workerdeta0_.city as city0_0_, workerdeta0_.country as country0_0_, workerdeta0_.state as state0_0_, workerdeta0_.street as street0_0_ from workerdetail workerdeta0_ where workerdeta0_.worker_id=?
Sushmita , Dasgupta, West Bengal
Nayana , Ahuja, Uttar Pradesh
Sushmita , Dasgupta, West Bengal
Nayana , Ahuja, Uttar Pradesh

In worker table, you will get the following record :

In workerdetail table, you will get the following record :

Download Source Code

Advertisements

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: February 25, 2012

Related Tutorials

Discuss: Hibernate One to One Bi-directional Mapping  

Post your Comment


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