- Hibernate 教程
- Hibernate - 首頁
- ORM - 概述
- Hibernate - 概述
- Hibernate - 架構
- Hibernate - 環境
- Hibernate - 配置
- Hibernate - 會話
- Hibernate - 持久化類
- Hibernate - 對映檔案
- Hibernate - 對映型別
- Hibernate - 示例
- Hibernate - O/R 對映
- Hibernate - 級聯型別
- Hibernate - 註解
- Hibernate - 查詢語言
- Hibernate - Criteria 查詢
- Hibernate - 原生 SQL
- Hibernate - 快取
- Hibernate - 實體生命週期
- Hibernate - 批處理
- Hibernate - 攔截器
- Hibernate - ID 生成器
- Hibernate - 儲存圖片
- Hibernate - log4j 整合
- Hibernate - Spring 整合
- Hibernate - Struts 2 整合
- Hibernate - Web 應用程式
- 對映表示例
- Hibernate - 表繼承策略(每個層次結構一張表)
- Hibernate - 表繼承策略(每個具體類一張表)
- Hibernate - 表繼承策略(每個子類一張表)
- Hibernate 有用資源
- Hibernate - 問題和解答
- Hibernate - 快速指南
- Hibernate - 有用資源
- Hibernate - 討論
Hibernate - 一對多對映
一對多對映可以使用Set Java 集合來實現,該集合不包含任何重複元素。我們已經瞭解瞭如何在 Hibernate 中對映Set集合,所以如果您已經學習了Set對映,那麼您就可以開始進行一對多映射了。
Set 在對映表中使用 <set> 元素進行對映,並使用 java.util.HashSet 進行初始化。當集合中不需要重複元素時,您可以在類中使用 Set 集合。
定義 RDBMS 表
考慮我們需要將員工記錄儲存在 EMPLOYEE 表中,該表將具有以下結構:
create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );
此外,假設每個員工可以擁有一個或多個與之相關的證書。因此,我們將證書相關資訊儲存在具有以下結構的單獨表中:
create table CERTIFICATE ( id INT NOT NULL auto_increment, certificate_name VARCHAR(30) default NULL, employee_id INT default NULL, PRIMARY KEY (id) );
EMPLOYEE 和 CERTIFICATE 物件之間將存在一對多關係:
定義 POJO 類
讓我們實現我們的 POJO 類Employee,它將用於持久化與 EMPLOYEE 表相關的物件,並在Set變數中包含證書的集合。
import java.util.*;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
private Set certificates;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
public Set getCertificates() {
return certificates;
}
public void setCertificates( Set certificates ) {
this.certificates = certificates;
}
}
現在,讓我們定義另一個與 CERTIFICATE 表對應的 POJO 類,以便可以將證書物件儲存和檢索到 CERTIFICATE 表中。此類還應實現 equals() 和 hashCode() 方法,以便 Java 可以確定任何兩個元素/物件是否相同。
public class Certificate {
private int id;
private String name;
public Certificate() {}
public Certificate(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public boolean equals(Object obj) {
if (obj == null) return false;
if (!this.getClass().equals(obj.getClass())) return false;
Certificate obj2 = (Certificate)obj;
if((this.id == obj2.getId()) && (this.name.equals(obj2.getName()))) {
return true;
}
return false;
}
public int hashCode() {
int tmp = 0;
tmp = ( id + name ).hashCode();
return tmp;
}
}
定義 Hibernate 對映檔案
讓我們開發我們的對映檔案,該檔案指示 Hibernate 如何將定義的類對映到資料庫表。
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
<meta attribute = "class-description">
This class contains the employee detail.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>
<set name = "certificates" cascade="all">
<key column = "employee_id"/>
<one-to-many class="Certificate"/>
</set>
<property name = "firstName" column = "first_name" type = "string"/>
<property name = "lastName" column = "last_name" type = "string"/>
<property name = "salary" column = "salary" type = "int"/>
</class>
<class name = "Certificate" table = "CERTIFICATE">
<meta attribute = "class-description">
This class contains the certificate records.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>
<property name = "name" column = "certificate_name" type = "string"/>
</class>
</hibernate-mapping>
您應該將對映文件儲存在格式為 <classname>.hbm.xml 的檔案中。我們將對映文件儲存在 Employee.hbm.xml 檔案中。您已經熟悉大多數對映細節,但讓我們再次檢視對映檔案的所有元素:
對映文件是一個 XML 文件,其中<hibernate-mapping>作為根元素,包含兩個與每個類對應的 <class> 元素。
<class>元素用於定義從 Java 類到資料庫表的特定對映。Java 類名使用 class 元素的name屬性指定,資料庫表名使用table屬性指定。
<meta>元素是可選元素,可用於建立類描述。
<id>元素將類中唯一的 ID 屬性對映到資料庫表的主鍵。id 元素的name屬性引用類中的屬性,column屬性引用資料庫表中的列。type屬性儲存 Hibernate 對映型別,這些對映型別將從 Java 轉換為 SQL 資料型別。
<generator>元素位於 id 元素內,用於自動生成主鍵值。generator 元素的class屬性設定為 native,讓 Hibernate 根據底層資料庫的功能選擇identity、sequence或hilo演算法來建立主鍵。
<property>元素用於將 Java 類屬性對映到資料庫表中的列。元素的name屬性引用類中的屬性,column屬性引用資料庫表中的列。type屬性儲存 Hibernate 對映型別,這些對映型別將從 Java 轉換為 SQL 資料型別。
<set>元素設定 Certificate 和 Employee 類之間的關係。我們在 <set> 元素中使用了cascade屬性來告訴 Hibernate 在同時持久化 Employee 物件時也持久化 Certificate 物件。name屬性設定為父類中定義的Set變數,在本例中為certificates。對於每個 set 變數,都需要在對映檔案中定義一個單獨的 set 元素。
<key>元素是 CERTIFICATE 表中儲存對父物件(即 EMPLOYEE 表)的外部索引鍵的列。
<one-to-many>元素表示一個 Employee 物件與多個 Certificate 物件相關聯。
建立應用程式類
最後,我們將建立我們的應用程式類,其中包含 main() 方法來執行應用程式。我們將使用此應用程式儲存一些員工記錄及其證書,然後我們將對這些記錄應用 CRUD 操作。
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Let us have a set of certificates for the first employee */
HashSet set1 = new HashSet();
set1.add(new Certificate("MCA"));
set1.add(new Certificate("MBA"));
set1.add(new Certificate("PMP"));
/* Add employee records in the database */
Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);
/* Another set of certificates for the second employee */
HashSet set2 = new HashSet();
set2.add(new Certificate("BCA"));
set2.add(new Certificate("BA"));
/* Add another employee record in the database */
Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);
/* List down all the employees */
ME.listEmployees();
/* Update employee's salary records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
ME.deleteEmployee(empID2);
/* List down all the employees */
ME.listEmployees();
}
/* Method to add an employee record in the database */
public Integer addEmployee(String fname, String lname, int salary, Set cert){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employee.setCertificates(cert);
employeeID = (Integer) session.save(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return employeeID;
}
/* Method to list all the employees detail */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator1 = employees.iterator(); iterator1.hasNext();){
Employee employee = (Employee) iterator1.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
Set certificates = employee.getCertificates();
for (Iterator iterator2 = certificates.iterator(); iterator2.hasNext();){
Certificate certName = (Certificate) iterator2.next();
System.out.println("Certificate: " + certName.getName());
}
}
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Method to update salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Method to delete an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
編譯和執行
以下是編譯和執行上述應用程式的步驟。在繼續進行編譯和執行之前,請確保已正確設定 PATH 和 CLASSPATH。
建立 hibernate.cfg.xml 配置檔案,如配置章節中所述。
建立 Employee.hbm.xml 對映檔案,如上所示。
建立 Employee.java 原始檔,如上所示,並編譯它。
建立 Certificate.java 原始檔,如上所示,並編譯它。
建立 ManageEmployee.java 原始檔,如上所示,並編譯它。
執行 ManageEmployee 二進位制檔案以執行程式。
您將在螢幕上看到以下結果,同時在 EMPLOYEE 和 CERTIFICATE 表中建立記錄。
$java ManageEmployee .......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ First Name: Manoj Last Name: Kumar Salary: 4000 Certificate: MBA Certificate: PMP Certificate: MCA First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA Certificate: BA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: MBA Certificate: PMP Certificate: MCA
如果您檢查您的 EMPLOYEE 和 CERTIFICATE 表,它們應該具有以下記錄:
mysql> select * from employee; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec) mysql> select * from certificate; +----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0.00 sec) mysql>