- Hibernate 教程
- Hibernate - 首頁
- ORM - 概述
- Hibernate - 概述
- Hibernate - 架構
- Hibernate - 環境
- Hibernate - 配置
- Hibernate - 會話
- Hibernate - 持久化類
- Hibernate - 對映檔案
- Hibernate - 對映型別
- Hibernate - 示例
- Hibernate - 物件關係對映
- 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, PRIMARY KEY (id) );
現在,為了在EMPLOYEE和CERTIFICATE物件之間實現多對多關係,我們必須引入另一箇中間表,其中包含員工ID和證書ID,如下所示:
create table EMP_CERT ( employee_id INT NOT NULL, certificate_id INT NOT NULL, PRIMARY KEY (employee_id,certificate_id) );
定義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如何將定義的類對映到資料庫表。<set>元素將用於定義多對多關係的規則。
<?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="save-update" table="EMP_CERT">
<key column = "employee_id"/>
<many-to-many column = "certificate_id" 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資料型別。
id元素中的<generator>元素用於自動生成主鍵值。generator元素的class屬性設定為native,以便Hibernate根據底層資料庫的功能選擇identity、sequence或hilo演算法來建立主鍵。
<property>元素用於將Java類屬性對映到資料庫表中的列。元素的name屬性引用類中的屬性,column屬性引用資料庫表中的列。type屬性包含Hibernate對映型別,此對映型別將從Java轉換為SQL資料型別。
<set>元素設定Certificate和Employee類之間的關係。我們將cascade屬性設定為save-update,以告訴Hibernate在同時執行Employee物件的SAVE(即CREATE和UPDATE)操作時持久化Certificate物件。name屬性設定為父類中定義的Set變數,在我們的例子中是certificates。對於每個set變數,我們需要在對映檔案中定義一個單獨的set元素。這裡我們使用name屬性將中間表名稱設定為EMP_CERT。
<key>元素是EMP_CERT表中儲存指向父物件(即表EMPLOYEE)的外部索引鍵的列,並連結到CERTIFICATE表中的certification_id。
<many-to-many>元素指示一個Employee物件與多個Certificate物件相關,並且column屬性用於連結中間表EMP_CERT。
建立應用程式類
最後,我們將建立包含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 certificates = new HashSet();
certificates.add(new Certificate("MCA"));
certificates.add(new Certificate("MBA"));
certificates.add(new Certificate("PMP"));
/* Add employee records in the database */
Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, certificates);
/* Add another employee record in the database */
Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, certificates);
/* 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、EMP_CERT和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: MBA Certificate: PMP Certificate: MCA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: MBA Certificate: PMP Certificate: MCA
如果您檢查EMPLOYEE、EMP_CERT和CERTIFICATE表,它們應該具有以下記錄:
mysql> select * from EMPLOYEE; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 22 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec) mysql> select * from CERTIFICATE; +----+------------------+ | id | certificate_name | +----+------------------+ | 4 | MBA | | 5 | PMP | | 6 | MCA | +----+------------------+ 3 rows in set (0.00 sec) mysql> select * from EMP_CERT; +-------------+----------------+ | employee_id | certificate_id | +-------------+----------------+ | 22 | 4 | | 22 | 5 | | 22 | 6 | +-------------+----------------+ 3 rows in set (0.00 sec) mysql>