Wednesday, January 4, 2012

One To One Mapping
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

public class Person {

 private int personID;

 public String personName;

 private PersonDetails myPersonDetails;

 public int getPersonID() {
  return personID;

 public void setPersonID(int personID) {
  this.personID = personID;

 public String getPersonName() {
  return personName;

 public void setPersonName(String personName) {
  this.personName = personName;

 @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
 public PersonDetails getMyPersonDetails() {
  return myPersonDetails;

 public void setMyPersonDetails(PersonDetails myPersonDetails) {
  this.myPersonDetails = myPersonDetails;

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

public class PersonDetails {

 private int personDetailID;

 private String zipCode;

 private String job;

 private double income;

 @Column(name="datailid_pk ")
 public int getPersonDetailID() {
  return personDetailID;

 public void setPersonDetailID(int personDetailID) {
  this.personDetailID = personDetailID;

 public String getZipCode() {
  return zipCode;

 public void setZipCode(String zipCode) {
  this.zipCode = zipCode;

 public String getJob() {
  return job;

 public void setJob(String job) {
  this.job = job;

 public double getIncome() {
  return income;

 public void setIncome(double income) {
  this.income = income;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class Test {

  * @param args
 public static void main(String[] args) {
  AnnotationConfiguration config=new AnnotationConfiguration();
  new SchemaExport(config).create(true, true);
  SessionFactory factory=config.buildSessionFactory();
  Session session=factory.getCurrentSession();
  PersonDetails pd1=new PersonDetails();
  pd1.setJob("Software Engineer");
  Person p1=new Person();
  p1.setPersonName("Kanishka Dilshan");


New Annotations :

  • @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER) : This annotation denotes the class has 1 to 1 
 When we load Person object PersonDetails object is also loaded with it since  FetchType is EAGER

Remember that this is a uni directional association. since we don't cant load Person objects using PersonDetails objects.


Post a Comment

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis