Wednesday, August 3, 2011

Relationships explored

Relationships explored


In this blog we will go through a use case which will demonstrate one to one relationship,one to many relationship and many to many relationship in Hibernate.Both flavors of one to one relationship will be explained.One to one relationship can be done using shared primary key as well as through foriegn key mapping.


Use Case:-

i)Here we are having one to many relationship between department and employee.One department can have many employees.But one employee belongs to one department only.

ii)There is many to many relationship between employee and address.Same address can belong to multiple employees and vice versa.

iii)There is one to one relationship between employee and salary account having shared primary key association between them.

iv)There is one to one relationship between employee and family history with family history containing employee id as foreign key.

Entity relationship diagram shows the relationship.



SQL Script:-

-- There is one to many relationship between department and employees
CREATE TABLE ORM_Department (
 Id bigint IDENTITY (1, 1) NOT NULL PRIMARY KEY,
 Name varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 Location varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
) 

CREATE TABLE ORM_Employee (
 Id bigint IDENTITY (1, 1) NOT NULL PRIMARY KEY ,
 Name varchar (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 BirthDate datetime NOT NULL ,
 DeptId bigint NOT NULL 
)


CREATE TABLE ORM_Address (
 Id bigint IDENTITY (1, 1) NOT NULL PRIMARY KEY,
 AddrLine varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 City varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 Country varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 PhoneNum varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
) 

--There is many to many relationship between employee and address 
CREATE TABLE ORM_EmpAddrMpg (
 AddrId bigint NOT NULL ,
 EmpId bigint NOT NULL 
)

--There is one to one relationship between employee and family history
--with foriegn key of employee in family history
CREATE TABLE ORM_FamilyHistory (
 Id bigint IDENTITY (1, 1) NOT NULL PRIMARY KEY,
 SpouseName varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
 FatherName varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 MotherName varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 NoOfKids int NOT NULL ,
 EmpId bigint NOT NULL 
) 

--There is one to one relationshiip between employee and salary account
--with shared primary key between salaccount and employee
CREATE TABLE ORM_SalAccount (
 Id bigint NOT NULL ,
 BankName varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 AcctNumber varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL 
) 


ALTER TABLE ORM_Employee
ADD FOREIGN KEY (DeptId) REFERENCES ORM_Department(ID);


ALTER TABLE ORM_EmpAddrMpg
ADD PRIMARY KEY(AddrId,EmpId);


ALTER TABLE ORM_EmpAddrMpg
ADD FOREIGN KEY (EmpId) REFERENCES ORM_Employee(ID);


ALTER TABLE ORM_EmpAddrMpg
ADD FOREIGN KEY (AddrId) REFERENCES ORM_Address(ID);


ALTER TABLE ORM_FamilyHistory
ADD FOREIGN KEY (EmpId) REFERENCES ORM_Employee(ID);


ALTER TABLE ORM_SalAccount
ADD FOREIGN KEY (Id) REFERENCES ORM_Employee(ID);


Model Classes:-

Department.java having collection of employees.Department is on the non owning side of the relationship.Thats why we have mappedBy attribute on empSet.

package com.kunaal.model;

import java.util.HashSet;
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.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;


/**
 * @author Kunaal A Trehan
 *
 */
@Entity
@Table(name="ORM_Department")
public class Department implements BaseModel<Long>{

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="id")
 private Long deptId;
 
 @Column(name="name")
 private String deptName;
 
 @Column(name="location")
 private String deptLoc;
 
 @OneToMany(mappedBy="dept")
 @Cascade(value = { CascadeType.SAVE_UPDATE })
 private Set<Employee> empSet=new HashSet<Employee>();

 /**
  * @return the deptId
  */
 public Long getDeptId() {
  return deptId;
 }

 /**
  * @param deptId the deptId to set
  */
 public void setDeptId(Long deptId) {
  this.deptId = deptId;
 }

 /**
  * @return the deptName
  */
 public String getDeptName() {
  return deptName;
 }

 /**
  * @param deptName the deptName to set
  */
 public void setDeptName(String deptName) {
  this.deptName = deptName;
 }

 /**
  * @return the deptLoc
  */
 public String getDeptLoc() {
  return deptLoc;
 }

 /**
  * @param deptLoc the deptLoc to set
  */
 public void setDeptLoc(String deptLoc) {
  this.deptLoc = deptLoc;
 }

 
 /**
  * Overriden hashcode method
  */
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((deptId == null) ? 0 : deptId.hashCode());
  return result;
 }

 /**
  * Overriden equals method using department id as identifier
  */
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Department other = (Department) obj;
  if (deptId == null) {
   if (other.deptId != null)
    return false;
  } else if (!deptId.equals(other.deptId))
   return false;
  return true;
 }

 /**
  * @return the empSet
  */
 public Set<Employee> getEmpSet() {
  return empSet;
 }

 /**
  * @param empSet the empSet to set
  */
 public void setEmpSet(Set<Employee> empSet) {
  this.empSet = empSet;
 }

 public Long getPrimaryKey() {
  return getDeptId();
 }

 
}


Address.java having many to many relationship with employee and on the non owning side of the relationship.Thats why we have mappedBy attribute on empSet.

package com.kunaal.model;

import java.util.HashSet;
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.ManyToMany;
import javax.persistence.Table;

/**
 * @author Kunaal A Trehan
 *
 */
@Entity
@Table(name="ORM_Address")
public class Address implements BaseModel<Long>{

 @Id
 @Column(name="id")
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long addrId;
 
 @Column(name="addrLine")
 private String addrDetails;
 
 @Column(name="city")
 private String addrCity;
 
 @Column(name="country")
 private String addrCtry;
 
 @Column(name="phoneNum")
 private String phoneNum;
 
 @ManyToMany(mappedBy="addrSet")
 private Set<Employee> empSet=new HashSet<Employee>();
 

 /**
  * @return the addrId
  */
 public Long getAddrId() {
  return addrId;
 }

 /**
  * @param addrId the addrId to set
  */
 public void setAddrId(Long addrId) {
  this.addrId = addrId;
 }

 /**
  * @return the addrDetails
  */
 public String getAddrDetails() {
  return addrDetails;
 }

 /**
  * @param addrDetails the addrDetails to set
  */
 public void setAddrDetails(String addrDetails) {
  this.addrDetails = addrDetails;
 }

 /**
  * @return the addrCity
  */
 public String getAddrCity() {
  return addrCity;
 }

 /**
  * @param addrCity the addrCity to set
  */
 public void setAddrCity(String addrCity) {
  this.addrCity = addrCity;
 }

 /**
  * @return the addrCtry
  */
 public String getAddrCtry() {
  return addrCtry;
 }

 /**
  * @param addrCtry the addrCtry to set
  */
 public void setAddrCtry(String addrCtry) {
  this.addrCtry = addrCtry;
 }

 /**
  * @return the phoneNum
  */
 public String getPhoneNum() {
  return phoneNum;
 }

 /**
  * @param phoneNum the phoneNum to set
  */
 public void setPhoneNum(String phoneNum) {
  this.phoneNum = phoneNum;
 }

 

 /**
  * @return the empSet
  */
 public Set<Employee> getEmpSet() {
  return empSet;
 }

 /**
  * @param empSet the empSet to set
  */
 public void setEmpSet(Set<Employee> empSet) {
  this.empSet = empSet;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#hashCode()
  */
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result
    + ((addrCity == null) ? 0 : addrCity.hashCode());
  result = prime * result
    + ((addrCtry == null) ? 0 : addrCtry.hashCode());
  result = prime * result
    + ((addrDetails == null) ? 0 : addrDetails.hashCode());
  result = prime * result + ((addrId == null) ? 0 : addrId.hashCode());
  result = prime * result + ((empSet == null) ? 0 : empSet.hashCode());
  result = prime * result
    + ((phoneNum == null) ? 0 : phoneNum.hashCode());
  return result;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#equals(java.lang.Object)
  */
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Address other = (Address) obj;
  if (addrCity == null) {
   if (other.addrCity != null)
    return false;
  } else if (!addrCity.equals(other.addrCity))
   return false;
  if (addrCtry == null) {
   if (other.addrCtry != null)
    return false;
  } else if (!addrCtry.equals(other.addrCtry))
   return false;
  if (addrDetails == null) {
   if (other.addrDetails != null)
    return false;
  } else if (!addrDetails.equals(other.addrDetails))
   return false;
  if (addrId == null) {
   if (other.addrId != null)
    return false;
  } else if (!addrId.equals(other.addrId))
   return false;
  if (empSet == null) {
   if (other.empSet != null)
    return false;
  } else if (!empSet.equals(other.empSet))
   return false;
  if (phoneNum == null) {
   if (other.phoneNum != null)
    return false;
  } else if (!phoneNum.equals(other.phoneNum))
   return false;
  return true;
 }

 public Long getPrimaryKey() {
  return getAddrId();
 }
}

FamilyHistory.java having one to one relationship with employee with empId as foreign key.We have Join Column annotation stating the column mapping.Since FamilyHistory owns the relationship ,so we donot have mappedBy attribute.


package com.kunaal.model;

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;
import javax.persistence.Table;

/**
 * @author Kunaal A Trehan
 *
 */
@Entity
@Table(name="ORM_FamilyHistory")
public class FamilyHistory {
 
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="id")
 private Long famHistId;
 
 @Column(name="SpouseName")
 private String spouseName;
 
 @Column(name="FatherName")
 private String fatherName;
 
 @Column(name="MotherName")
 private String motherName;
 
 @Column(name="NoOfKids")
 private Integer noOfKids;
 
 @OneToOne
 @JoinColumn(name="empId")
 private Employee emp;

 /**
  * @return the famHistId
  */
 public Long getFamHistId() {
  return famHistId;
 }

 /**
  * @param famHistId the famHistId to set
  */
 public void setFamHistId(Long famHistId) {
  this.famHistId = famHistId;
 }

 /**
  * @return the spouseName
  */
 public String getSpouseName() {
  return spouseName;
 }

 /**
  * @param spouseName the spouseName to set
  */
 public void setSpouseName(String spouseName) {
  this.spouseName = spouseName;
 }

 /**
  * @return the fatherName
  */
 public String getFatherName() {
  return fatherName;
 }

 /**
  * @param fatherName the fatherName to set
  */
 public void setFatherName(String fatherName) {
  this.fatherName = fatherName;
 }

 /**
  * @return the motherName
  */
 public String getMotherName() {
  return motherName;
 }

 /**
  * @param motherName the motherName to set
  */
 public void setMotherName(String motherName) {
  this.motherName = motherName;
 }

 /**
  * @return the noOfKids
  */
 public Integer getNoOfKids() {
  return noOfKids;
 }

 /**
  * @param noOfKids the noOfKids to set
  */
 public void setNoOfKids(Integer noOfKids) {
  this.noOfKids = noOfKids;
 }

 /**
  * @return the emp
  */
 public Employee getEmp() {
  return emp;
 }

 /**
  * @param emp the emp to set
  */
 public void setEmp(Employee emp) {
  this.emp = emp;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#hashCode()
  */
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result
    + ((famHistId == null) ? 0 : famHistId.hashCode());
  return result;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#equals(java.lang.Object)
  */
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  FamilyHistory other = (FamilyHistory) obj;
  if (famHistId == null) {
   if (other.famHistId != null)
    return false;
  } else if (!famHistId.equals(other.famHistId))
   return false;
  return true;
 }
}

SalaryAcct.java having one to one relationship with employee.Both SalaryAcct and Employee share the same primary key.In SalaryAcct we have created a GenericGenerator with strategy as foreign and using it for id mapping.Moreover on employee property besides One to One Mapping we have one more mapping of PrimaryKeyJoinColumn

package com.kunaal.model;

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

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

/**
 * @author Kunaal A Trehan
 *
 */
@Entity
@Table(name="ORM_SalAccount")
public class SalaryAcct {
 
 @GenericGenerator(name="pkGen" ,strategy="foreign",
   parameters=@Parameter(name="property",value="emp")) 
 @Id
 @GeneratedValue(generator="pkGen")
 @Column(name="Id", unique = true, nullable = false)
 private Long salAcctId;
 
 @Column(name="BankName")
 private String bankName;
 
 @Column(name="AcctNumber")
 private String acctNumber;
 
 @OneToOne
 @PrimaryKeyJoinColumn
 private Employee emp;

 /**
  * @return the salAcctId
  */
 public Long getSalAcctId() {
  return salAcctId;
 }

 /**
  * @param salAcctId the salAcctId to set
  */
 public void setSalAcctId(Long salAcctId) {
  this.salAcctId = salAcctId;
 }

 /**
  * @return the bankName
  */
 public String getBankName() {
  return bankName;
 }

 /**
  * @param bankName the bankName to set
  */
 public void setBankName(String bankName) {
  this.bankName = bankName;
 }

 /**
  * @return the acctNumber
  */
 public String getAcctNumber() {
  return acctNumber;
 }

 /**
  * @param acctNumber the acctNumber to set
  */
 public void setAcctNumber(String acctNumber) {
  this.acctNumber = acctNumber;
 }

 /**
  * @return the emp
  */
 public Employee getEmp() {
  return emp;
 }

 /**
  * @param emp the emp to set
  */
 public void setEmp(Employee emp) {
  this.emp = emp;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#hashCode()
  */
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result
    + ((salAcctId == null) ? 0 : salAcctId.hashCode());
  return result;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#equals(java.lang.Object)
  */
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  SalaryAcct other = (SalaryAcct) obj;
  if (salAcctId == null) {
   if (other.salAcctId != null)
    return false;
  } else if (!salAcctId.equals(other.salAcctId))
   return false;
  return true;
 }

}

Employee.java containing ManytoOne relationship with department,ManytoMany with address,OneToOne with FamilyHistory,OneToOne having shared primary key with salary account.
Here employee is the owner of the many to many relationship with address.But it is on non owning side for one to one relationship with family history and salary account


package com.kunaal.model;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;

/**
 * Model class showing 
 * -ManytoOne relationship with department
 * -ManytoMany with address
 * -OneToOne with FamilyHistory
 * -OneToOne having shared primary key with salary account
 * 
 * @author Kunaal A Trehan
 *
 */
@Entity
@Table(name="ORM_Employee")
public class Employee implements BaseModel<Long>{

 @Id
 @Column(name="id")
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long empId;
 
 @Column(name="name")
 private String empName;
 
 @Column(name="birthDate")
 private Date birthDate;
 
 @ManyToOne
 @Cascade(value={org.hibernate.annotations.CascadeType.SAVE_UPDATE})
 @JoinColumn(name="DeptId")
 private Department dept;
 
 @ManyToMany(cascade=CascadeType.ALL)
 @JoinTable(name="ORM_EmpAddrMpg",
    joinColumns=@JoinColumn(name="EmpId"),
    inverseJoinColumns=@JoinColumn(name="AddrId"))
 private Set<Address> addrSet=new HashSet<Address>();
 
 @OneToOne(cascade=CascadeType.ALL,mappedBy="emp")
 private FamilyHistory famHistory;
 
 @OneToOne(cascade=CascadeType.ALL,mappedBy="emp")
 private SalaryAcct salAcct;

 /**
  * @return the empId
  */
 public Long getEmpId() {
  return empId;
 }

 /**
  * @param empId the empId to set
  */
 public void setEmpId(Long empId) {
  this.empId = empId;
 }

 /**
  * @return the empName
  */
 public String getEmpName() {
  return empName;
 }

 /**
  * @param empName the empName to set
  */
 public void setEmpName(String empName) {
  this.empName = empName;
 }

 /**
  * @return the birthDate
  */
 public Date getBirthDate() {
  return birthDate;
 }

 /**
  * @param birthDate the birthDate to set
  */
 public void setBirthDate(Date birthDate) {
  this.birthDate = birthDate;
 }

 /**
  * @return the dept
  */
 public Department getDept() {
  return dept;
 }

 /**
  * @param dept the dept to set
  */
 public void setDept(Department dept) {
  this.dept = dept;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#hashCode()
  */
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((empId == null) ? 0 : empId.hashCode());
  return result;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#equals(java.lang.Object)
  */
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Employee other = (Employee) obj;
  if (empId == null) {
   if (other.empId != null)
    return false;
  } else if (!empId.equals(other.empId))
   return false;
  return true;
 }

 /**
  * @return the addrSet
  */
 public Set<Address> getAddrSet() {
  return addrSet;
 }

 /**
  * @param addrSet the addrSet to set
  */
 public void setAddrSet(Set<Address> addrSet) {
  this.addrSet = addrSet;
 }

 /**
  * @return the famHistory
  */
 public FamilyHistory getFamHistory() {
  return famHistory;
 }

 /**
  * @param famHistory the famHistory to set
  */
 public void setFamHistory(FamilyHistory famHistory) {
  this.famHistory = famHistory;
 }

 /**
  * @return the salAcct
  */
 public SalaryAcct getSalAcct() {
  return salAcct;
 }

 /**
  * @param salAcct the salAcct to set
  */
 public void setSalAcct(SalaryAcct salAcct) {
  this.salAcct = salAcct;
 }

 public Long getPrimaryKey() {
  return getEmpId();
 }
}


Testcase for inserting employee information.Here we are creating the objects and associating it as per different types of relationships


package com.kunaal.service;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.kunaal.model.Address;
import com.kunaal.model.Department;
import com.kunaal.model.Employee;
import com.kunaal.model.FamilyHistory;
import com.kunaal.model.SalaryAcct;

/**
 * @author Kunaal A Trehan
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-main.xml"})
@TransactionConfiguration(defaultRollback=false)
public class EmplServiceTest implements ApplicationContextAware{

 private ApplicationContext appCtx;

 @Autowired
 private IEmplService emplService;
 
 public void setApplicationContext(ApplicationContext appCtx)
   throws BeansException {
  this.appCtx=appCtx;
 }
 
 @Test
 @Transactional
 public void insertEmployee(){
  Employee employee=createEmployee();
  emplService.persist(employee);
 }
 
 
 /**
  * Utility method for creating employee entity
  * 
  * @return
  */
 private static Employee createEmployee(){
  Employee emp=new Employee();
  
  Department dept=createDepartment();
  FamilyHistory famHistory=createFamilyHistory();
  SalaryAcct salAcct=createSalAcct();
  Address permAddr=createPermAddr();
  Address tempAddr=createTempAddr();
  Set<Address> addrSet=new HashSet<Address>();
  
  
  emp.setBirthDate(new Date());  
  emp.setEmpName("Kunaal A Trehan");

  //Make the associations
  //1.One to many association between employee and dept with employee having foreign key of dept
  //So employee is owner of association.
  dept.getEmpSet().add(emp);
  emp.setDept(dept);
  
  //2.One to one association between employee and family history with foreign key 
  //in family history side.So family history is owner of association
  emp.setFamHistory(famHistory);
  famHistory.setEmp(emp);
  
  //3.Many to many association between employee and address with employee being owner of relationship.
  permAddr.getEmpSet().add(emp);
  tempAddr.getEmpSet().add(emp);
  addrSet.add(permAddr);
  addrSet.add(tempAddr);
  emp.setAddrSet(addrSet);

  //4.One to one relationship between employee and salary account
  //with shared primary key
  emp.setSalAcct(salAcct);
  salAcct.setEmp(emp);  
  return emp;
 }

 /**
  * 
  * @return
  */
 private static Department createDepartment(){
  Department dept=new Department();
 
  dept.setDeptLoc("Bangalore");
  dept.setDeptName("HR");
  
  return dept;
 }
 
 private static FamilyHistory createFamilyHistory(){
  FamilyHistory famHist=new FamilyHistory();
  famHist.setFatherName("Mr. Arun Verma");
  famHist.setMotherName("Ms Nalini Verma");
  famHist.setNoOfKids(new Integer(1));
  famHist.setSpouseName("Ms Gunjan");
  
  return famHist;
 }
 
 private static Address createTempAddr(){
  Address address=new Address();
  
  address.setAddrCity("Bangalore");
  address.setAddrCtry("India");
  address.setAddrDetails("CV Raman Nagar");
  address.setPhoneNum("1234444");
  return address;
 }
 
 private static Address createPermAddr(){
  Address address=new Address();
  
  address.setAddrCity("Hoshiarpur");
  address.setAddrCtry("India");
  address.setAddrDetails("Ram Nagar");
  address.setPhoneNum("123433444");
  return address;
 }
 
 private static SalaryAcct createSalAcct(){
  SalaryAcct salAcct=new SalaryAcct();
  
  salAcct.setAcctNumber("12345578");
  salAcct.setBankName("ICICI");
  return salAcct;
 }

 
}

Test Case output.Since we were using bidirectional relationship.There is no update query for foreign key values

INFO: Building new Hibernate SessionFactory
Aug 4, 2011 12:30:33 AM org.springframework.test.context.transaction.TransactionalTestExecutionListener startNewTransaction
INFO: Began transaction (1): transaction manager [org.springframework.orm.hibernate3.HibernateTransactionManager@24e801]; rollback [false]
Hibernate: insert into ORM_Department (location, name) values (?, ?)
Hibernate: insert into ORM_Employee (birthDate, DeptId, name) values (?, ?, ?)
Hibernate: insert into ORM_Address (city, country, addrLine, phoneNum) values (?, ?, ?, ?)
Hibernate: insert into ORM_Address (city, country, addrLine, phoneNum) values (?, ?, ?, ?)
Hibernate: insert into ORM_FamilyHistory (empId, FatherName, MotherName, NoOfKids, SpouseName) values (?, ?, ?, ?, ?)
Hibernate: insert into ORM_SalAccount (AcctNumber, BankName, Id) values (?, ?, ?)
Hibernate: insert into ORM_EmpAddrMpg (EmpId, AddrId) values (?, ?)
Hibernate: insert into ORM_EmpAddrMpg (EmpId, AddrId) values (?, ?)
Aug 4, 2011 12:30:34 AM org.springframework.test.context.transaction.TransactionalTestExecutionListener endTransaction
INFO: Committed transaction after test execution for test context [[TestContext@83e5f1 testClass = EmplServiceTest, locations = array<String>['classpath:spring-main.xml'], testInstance = com.kunaal.service.EmplServiceTest@16d64c5, testMethod = insertEmployee@EmplServiceTest, testException = [null]]]

No comments:

Post a Comment