Relationship One-To-One in Hibernate


Tiếp tục lượt bài Hibernate hôm nay mình sẻ hướng dẩn các bạn thể hiện mối quan hệ 1-1 trong hibernate.

Source code : download

Chúng ta tạo CSDL như hình sau :

d1

Cấu trúc thư mục của chúng ta :

d1

Class employee.java


package thaihoanghai.hibernate.bean;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="employee")
public class Employee {
 @Id
 @GeneratedValue
 @Column(name="employee_id")
 private int employeeId;

 @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="employee",cascade=CascadeType.ALL)
 private EmployeeDetail employeeDetail;

 public Employee(int employeeId, String firstName, String lastName,
 Date birthDate, String cellPhone) {
 super();
 this.employeeId = employeeId;
 this.firstName = firstName;
 this.lastName = lastName;
 this.birthDate = birthDate;
 this.cellPhone = cellPhone;
 }
 public Employee(String firstName, String lastName, Date birthDate,
 String cellPhone) {
 super();
 this.firstName = firstName;
 this.lastName = lastName;
 this.birthDate = birthDate;
 this.cellPhone = cellPhone;
 }
 public Employee() {
 super();
 // TODO Auto-generated constructor stub
 }
 public int getEmployeeId() {
 return employeeId;
 }
 public void setEmployeeId(int employeeId) {
 this.employeeId = employeeId;
 }
 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 EmployeeDetail getEmployeeDetail() {
 return employeeDetail;
 }
 public void setEmployeeDetail(EmployeeDetail employeeDetail) {
 this.employeeDetail = employeeDetail;
 }

}

Class EmployeeDetail.java

</pre>
package thaihoanghai.hibernate.bean;

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;

@Entity
@Table(name="employeedetail")
public class EmployeeDetail {
 @Id
 @Column(name="employee_id", unique=true, nullable=false)
 @GeneratedValue(generator="gen")
 @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property",value="employee"))
 private int employeeId;

 @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
 @PrimaryKeyJoinColumn
 private Employee employee;

 public EmployeeDetail(String street, String city, String state,
 String country) {
 super();
 this.street = street;
 this.city = city;
 this.state = state;
 this.country = country;
 }
 public int getEmployeeId() {
 return employeeId;
 }
 public void setEmployeeId(int employeeId) {
 this.employeeId = employeeId;
 }
 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 Employee getEmployee() {
 return employee;
 }
 public void setEmployee(Employee employee) {
 this.employee = employee;
 }
 public EmployeeDetail() {
 super();
 // TODO Auto-generated constructor stub
 }

}
<pre>

Class EmployeeDAO.java

</pre>
package thaihoanghai.hibernate.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import thaihoanghai.hibernate.bean.Employee;
import thaihoanghai.hibernate.bean.EmployeeDetail;
import thaihoanghai.hibernate.util.HibernateUtil;

public class EmployeeDAO {
 public boolean addEmployee(Employee emp,EmployeeDetail empDetail){
 boolean flag = false;
 Transaction trns = null;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 emp.setEmployeeDetail(empDetail);
 empDetail.setEmployee(emp);
 session.save(emp);
 trns.commit();
 flag = true;
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 e.printStackTrace();
 }finally{
 session.flush();
 session.close();
 }
 return flag;
 }

 @SuppressWarnings("unchecked")
 public List<Employee> getListEmployee(){
 List<Employee> employeeList = new ArrayList<Employee>();
 Transaction trns = null;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 employeeList = session.createQuery("from Employee").list();// Note Employee
 trns.commit();

 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 e.printStackTrace();
 }finally{
 session.flush();
 session.close();
 }
 return employeeList;
 }
}
<pre>

Class EmployeeService.java

</pre>
package thaihoanghai.hibernate.service;

import java.util.List;

import thaihoanghai.hibernate.bean.Employee;
import thaihoanghai.hibernate.bean.EmployeeDetail;
import thaihoanghai.hibernate.dao.EmployeeDAO;

public class EmployeeService {
 EmployeeDAO employeeDAO = new EmployeeDAO();

 public boolean addEmployee(Employee emp, EmployeeDetail empDetail){
 return employeeDAO.addEmployee(emp, empDetail);
 }

 public List<Employee> getListEmployee(){
 return employeeDAO.getListEmployee();
 }
}
<pre>

class HibernateUtils.java (Không thay đổi so với bài trước)

</pre>
package thaihoanghai.hibernate.util;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate Util used to configure Hibernate's Session Factoru and retrieve it as Singleton
 * @author kobee
 *
 */
public class HibernateUtil {
 private static final SessionFactory seesionFactory;
 private static ServiceRegistry serviceRegistry;

 static{
 try {
 Configuration configuration = new Configuration();
 configuration.configure();
 serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
 seesionFactory = configuration.buildSessionFactory(serviceRegistry);

 } catch (HibernateException e) {
 System.err.println("Initial SessionFactoru creation failed. " + e);
 throw new ExceptionInInitializerError(e);
 }

 }

public static SessionFactory getSeesionfactory() {
 return seesionFactory;
 }

}
<pre>

file hibernate.cfg.xml

</pre>
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
 <session-factory>
 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="hibernate.connection.url">jdbc:mysql://localhost/mydatabase</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">123456</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

 <!-- JDBC connecition pool (use the built-in) -->
 <property name="hibernate.connection.pool_size">1</property>
 <!-- Enable Hibernate's automatic session context management -->
 <property name="hibernate.current_session_context_class">thread</property>

 <!-- Echo all executed SQL to stdout -->
 <property name="show_sql">true</property>
 <property name="format_sql">false</property>
 <property name="hbm2ddl.auto">Validate</property>

 <!-- Mapping to Resource -->
 <mapping class="thaihoanghai.hibernate.bean.Employee"/>
 <mapping class="thaihoanghai.hibernate.bean.EmployeeDetail"/>

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

Ok giờ chúng ta test thử nè :
Class Test.java:

</pre>
package project;

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

import thaihoanghai.hibernate.bean.Employee;
import thaihoanghai.hibernate.bean.EmployeeDetail;
import thaihoanghai.hibernate.service.EmployeeService;

public class Test {
 public static void main(String[] args) {
 EmployeeService service = new EmployeeService();
 try {

 //===========================Add Employee =======================================
 Date bod = new SimpleDateFormat("yyyy-MM-dd").parse("1991-10-10");
 Employee emp = new Employee("Kobee", "Bryan", bod, "0908-159-159");
 EmployeeDetail empDetail = new EmployeeDetail
 ("24/3Y TN P16 QGV","HCMHN","HCM-GV","QN-TP");
 boolean flag = service.addEmployee(emp, empDetail);
 if(flag)
 System.out.println("Insert Success");
 else
 System.out.println("Insert fail");

 //=============================Get List Employee==================================

 List<Employee> employeeList = service.getListEmployee();
 for(Employee e : employeeList){
 String value = "---------Employee List-----------"+"\n"+
 "ID: " + e.getEmployeeId() + "\nName: " + e.getLastName()+"\n"+
 "Street: " + e.getEmployeeDetail().getStreet();
 System.out.println(value);
 }
 } catch (Exception e) {
 e.printStackTrace();
 }

}
}
<pre>

OK Chúc các bạn thành công !!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: