One To Many in Hibernate


Tiếp theo lượt bài Hibernate hôm nay chúng ta sử dụng mối quan hệ 1 – N trong hibernate.

Source code : download

Note : các loạt bài Hibernate này mình đang viết cho phần model trên web . Nếu các bạn sử dụng trong application vẩn làm tương tự như vậy nha. (Tham khảo bài đầu để biết cách cấu hình : …)

Tạo csdl như hình vẻ sau :

d1

Cấu trúc thư mục như sau :

d1

Sau đây là source code của chương trình như sau :

Class Company.java


package thaihoanghai.hibernate.bean;

import java.util.Set;

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

@Entity
@Table(name="company")
public class Company {
 @Id
 @GeneratedValue
 @Column(name="company_id")
 private int companyId;

 @Column(name="company_name")
 private String companyName;

 @OneToMany(mappedBy="company")
 private Set<Employee> employees;

 public Company(String companyName) {
 this.companyName = companyName;
 }
 public Company() {
 super();
 // TODO Auto-generated constructor stub
 }
 public int getCompanyId() {
 return companyId;
 }
 public void setCompanyId(int companyId) {
 this.companyId = companyId;
 }
 public String getCompanyName() {
 return companyName;
 }
 public void setCompanyName(String companyName) {
 this.companyName = companyName;
 }
 public Set<Employee> getEmployees() {
 return employees;
 }
 public void setEmployees(Set<Employee> employees) {
 this.employees = employees;
 }

}

Class Employee.java


package thaihoanghai.hibernate.bean;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
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 birthDay;

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

 @ManyToOne
 @JoinColumn(name="company_id")
 private Company company;

 public Employee() {

 }
 public Employee(String firstName, String lastName, Date birthDay,
 String cellPhone) {
 super();
 this.firstName = firstName;
 this.lastName = lastName;
 this.birthDay = birthDay;
 this.cellPhone = cellPhone;
 }
 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 getBirthDay() {
 return birthDay;
 }
 public void setBirthDay(Date birthDay) {
 this.birthDay = birthDay;
 }
 public String getCellPhone() {
 return cellPhone;
 }
 public void setCellPhone(String cellPhone) {
 this.cellPhone = cellPhone;
 }
 public Company getCompany() {
 return company;
 }
 public void setCompany(Company company) {
 this.company = company;
 }
 @Override
 public String toString() {
 return "Employee [employeeId=" + employeeId + ", firstName="
 + firstName + ", lastName=" + lastName + ", birthDay="
 + birthDay + ", cellPhone=" + cellPhone + ", company="
 + company + "]";
 }
 @Override
 public int hashCode() {
 final int prime = 31;
 int result = 1;
 result = prime * result + employeeId;
 return result;
 }
 @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 (employeeId != other.employeeId)
 return false;
 return true;
 }

}

ManageEmployeeDAO.java


package thaihoanghai.hibernate.dao;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

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

public class ManageEmployeeDAO {
 public boolean addEmployee(Employee emp,Company company){
 Transaction trns = null;
 boolean flag = false;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 emp.setCompany(company);
 session.saveOrUpdate(emp);
 trns.commit();
 flag = true;
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 }finally{
 session.flush();
 session.close();
 }
 return flag;
 }

 public boolean addCompany(Company com){
 Transaction trns = null;
 boolean flag = false;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 session.saveOrUpdate(com);
 trns.commit();
 flag = true;
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 }finally{
 session.flush();
 session.close();
 }
 return flag;
 }

 public Company getCompanyWithID(int id){
 Transaction trns = null;
 Company com = null;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 com = (Company) session.get(Company.class, id);
 trns.commit();
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 }finally{
 session.flush();
 session.close();
 }
 return com;
 }

 public boolean deleteCompany(int id){
 Transaction trns = null;
 boolean flag = false;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 Company com = (Company) session.get(Company.class, id);
 session.delete(com);
 trns.commit();
 flag = true;
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 }finally{
 session.flush();
 session.close();
 }
 return flag;
 }

 public Set<Employee> getEmployeeList(){
 Set<Employee> employeeList = new HashSet<Employee>();
 Transaction trns = null;

 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 @SuppressWarnings("unchecked")
 List<Employee> list = session.createQuery("from Employee").list();
 employeeList.addAll(list);
 trns.commit();
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 }finally{
 session.flush();
 session.close();
 }
 return employeeList;
 }
}

ManageEmployeeService.java


package thaihoanghai.hibernate.service;

import java.util.Set;

import thaihoanghai.hibernate.bean.Company;
import thaihoanghai.hibernate.bean.Employee;
import thaihoanghai.hibernate.dao.ManageEmployeeDAO;

public class ManageEmployeeService {
 ManageEmployeeDAO manageEmployeeDAO = new ManageEmployeeDAO();

 public boolean addEmployee(Employee empl,Company company){
 return manageEmployeeDAO.addEmployee(empl,company);
 }

 public boolean addCompany(Company com){
 return manageEmployeeDAO.addCompany(com);
 }

 public Company getCompanyWithID(int id){
 return manageEmployeeDAO.getCompanyWithID(id);
 }

 public boolean deleteCompany(int id){
 return manageEmployeeDAO.deleteCompany(id);
 }

 public Set<Employee> getEmployeeList(){
 return manageEmployeeDAO.getEmployeeList();
 }
}

file hibernate.cfg.xml


<?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.Company"/>

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

Class HibernateUtil.java


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;
 }

}

Sau đây là class Text Chương Trình : Test.java


package project;

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

import thaihoanghai.hibernate.bean.Company;
import thaihoanghai.hibernate.bean.Employee;
import thaihoanghai.hibernate.service.ManageEmployeeService;

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

 Company company = new Company("Global Cyber Soft");
 service.addCompany(company);

 Employee e1 = new Employee("Kobee", "Thai",
 getDate("1991-10-10"), "0122-3525-xxx");

 Employee e2 = new Employee("Justina", "Sun",
 getDate("2005-10-01"), "0111-1115-xxx");

 //Company com = service.getCompanyWithID(1);
 service.addEmployee(e1, company);
 service.addEmployee(e2, company);

 service.deleteCompany(1);

 Set<Employee> employeeList = service.getEmployeeList();
 for(Employee e : employeeList){
 System.out.println(e.toString());
 }

 }

 private static Date getDate(String value){
 try {
 return new SimpleDateFormat("yyyy-mm-dd").parse(value);
 } catch (ParseException e) {
 e.printStackTrace();
 }
 return null;
 }
}

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: