Code ví dụ Hibernate One To Many (@OneToMany, @ManyToOne)

Code ví dụ Hibernate One To Many (@OneToMany, @ManyToOne)

(Xem thêm: Hướng dẫn tự học Hibernate)

(Xem thêm: Sự khác nhau giữa @OneToOne với @ManyToOne trong Hibernate)

Các công nghệ sử dụng:

Tạo database

Ở đây mình thực hiện tạo database gồm bảng company và bảng employee, mối quan hệ là 1 company có nhiều employee.

Tạo database và bảng:

CREATE SCHEMA `hibernate-demo` ;

CREATE TABLE `hibernate-demo`.`company` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `address` VARCHAR(255) NULL,
  PRIMARY KEY (`id`));

  
CREATE TABLE `hibernate-demo`.`employee` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `company_id` INT NULL,
  `name` VARCHAR(45) NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `emp-company`
    FOREIGN KEY (`company_id`)
    REFERENCES `hibernate-demo`.`company` (`id`));

Cấu trúc Project

Code ví dụ Hibernate One To Many (@OneToMany, @ManyToOne)

Các thư viện sử dụng

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>stackjava.com</groupId>
  <artifactId>HibernateOneToManyExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <hibernate.version>5.3.6.Final</hibernate.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>
  </dependencies>


</project>

Các class entities tương ứng

package stackjava.com.hibernatedemo.entities;

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

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

@Entity
@Table(name = "company")
public class Company {

  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "name")
  private String name;
  
  @OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
  private Set<Employee> listEmployee = new HashSet<>();

  // getter - setter

  @Override
  public String toString() {
    return "Company [id=" + id + ", name=" + name + "]";
  }
  
}
  • Annotation @OneToMany thực hiện mapping one to many. 1 đối tượng Company sẽ chứa nhiều đối tượng Employee (có thể là Set hoặc List)
  • mappedBy = "company" sẽ hiểu la mapping thông qua thuộc tính company trong class Employee
package stackjava.com.hibernatedemo.entities;

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

@Entity
@Table(name = "employee")
public class Employee {

  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;
  
  @Column(name = "name")
  private String name;
  
  @ManyToOne
  @JoinColumn(name = "company_id", nullable = false)
  private Company company;

  // getter - setter

  @Override
  public String toString() {
    return "Employee [id=" + id + ", name=" + name + ", company=" + company + "]";
  }
  
  
}
  • Annotation @ManyToOne thực hiện mapping many to one, nhiều đối tượng Employee sẽ cùng thuộc 1 đối tượng Company
  • Annotation @JoinColumn chỉ rõ thực hiện mapping qua field nào (ở đây là mapping qua column company_id trong table employee)

File cấu hình hibernate, kết nối tới MySQL

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
  <persistence-unit name="persistence">
    <description>Demo Hibernate Entity Manager</description>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
      <property name="javax.persistence.jdbc.url"
        value="jdbc:mysql://localhost:3306/hibernate-demo" />
      <property name="javax.persistence.jdbc.user" value="root" />
      <property name="javax.persistence.jdbc.password" value="admin1234" />
      <property name="hibernate.show_sql" value="true" />
    </properties>
  </persistence-unit>
</persistence>

Trong ví dụ này mình sử dụng entityManager nên sẽ khai báo file persistence.xml nếu các bạn sử dụng hibernateSession thì có thể khai báo file hibernate.cfg.xml

(Xem lại: Code ví dụ Hibernate EntityManager, EntityManagerFactory)

Demo 1:

Thực hiện insert 1 đối tượng Company và insert 2 đối tượng Customer cho đối tượng Company đó.

package stackjava.com.hibernatedemo.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import stackjava.com.hibernatedemo.entities.Company;
import stackjava.com.hibernatedemo.entities.Employee;

public class DemoInsert {

  public static void main(String[] args) {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();

    Company company = new Company();
    company.setName("Google");
    entityManager.persist(company);
    
    Employee emp1 = new Employee();
    emp1.setName("kai");
    emp1.setCompany(company);
    
    Employee emp2 = new Employee();
    emp2.setName("sena");
    emp2.setCompany(company);
    
    entityManager.persist(emp1);
    entityManager.persist(emp2);
    
    entityManager.getTransaction().commit();
    System.out.println("--------- after insert -------------");
    System.out.println(company);
    System.out.println(emp1);
    System.out.println(emp2);
    entityManager.close();
    entityManagerFactory.close();
  }

}

Kết quả:

Hibernate: insert into company (name) values (?)
Hibernate: insert into employee (company_id, name) values (?, ?)
Hibernate: insert into employee (company_id, name) values (?, ?)
--------- after insert -------------
Company [id=1, name=Google]
Employee [id=1, name=kai, company=Company [id=1, name=Google]]
Employee [id=2, name=sena, company=Company [id=1, name=Google]]

khi insert đối tượng employee, column company_id sẽ có giá trị là id của đối tượng company sau khi insert.

Demo 2:

Sau khi insert, ta thực hiện query xem có đúng là đối tượng Company có chứa nhiều đối tượng Employee không.

Ở ví dụ trên đối tượng company được tạo có id = 1 nên mình sẽ select đối tượng company có id = 1.

package stackjava.com.hibernatedemo.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import stackjava.com.hibernatedemo.entities.Company;

public class DemoSelect {

  public static void main(String[] args) {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();

    Company company = entityManager.find(Company.class, 1);
    System.out.println(company);
    
    company.getListEmployee().forEach(employee -> System.out.println(employee));
    
    entityManager.getTransaction().commit();
    entityManager.close();
    entityManagerFactory.close();
  }

}

Kết quả:

Hibernate: select company0_.id as id1_0_0_, company0_.name as name2_0_0_ from company company0_ where company0_.id=?
Company [id=1, name=Google]
Hibernate: select listemploy0_.company_id as company_3_1_0_, listemploy0_.id as id1_1_0_, listemploy0_.id as id1_1_1_, listemploy0_.company_id as company_3_1_1_, listemploy0_.name as name2_1_1_ from employee listemploy0_ where listemploy0_.company_id=?
Employee [id=2, name=sena, company=Company [id=1, name=Google]]
Employee [id=1, name=kai, company=Company [id=1, name=Google]]

Khi đối tượng Company thực hiện getListEmployee nó sẽ gọi câu truy vấn để select các đối tượng Employee của nó.

 

Okay, Done!

Download code ví dụ trên tại đây.

 

References:

https://docs.jboss.org/hibernate/…/OneToMany.html

stackjava.com