- 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 - 列表對映
列表是 Java 集合的一種,它按順序儲存元素並允許重複元素。此介面的使用者可以精確控制每個元素在列表中的插入位置。使用者可以透過其整數索引訪問元素,並在列表中搜索元素。更正式地說,列表通常允許元素對 e1 和 e2,使得 e1.equals(e2),並且如果它們允許空元素,則它們通常允許多個空元素。
列表在對映表中使用 <list> 元素對映,並使用 java.util.ArrayList 初始化。
定義 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, idx INT default NULL, employee_id INT default NULL, PRIMARY KEY (id) );
EMPLOYEE 和 CERTIFICATE 物件之間將存在一對多關係。
定義 POJO 類
讓我們實現一個 POJO 類Employee,它將用於持久化與 EMPLOYEE 表相關的物件,並在List變數中包含證書的集合。
import java.util.*;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
private List 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 List getCertificates() {
return certificates;
}
public void setCertificates( List certificates ) {
this.certificates = certificates;
}
}
我們需要定義另一個與 CERTIFICATE 表對應的 POJO 類,以便可以將證書物件儲存和檢索到 CERTIFICATE 表中。
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;
}
}
定義 Hibernate 對映檔案
讓我們開發我們的對映檔案,它指示 Hibernate 如何將定義的類對映到資料庫表。<list> 元素將用於定義對使用的列表集合的規則。列表的索引始終為整數型別,並使用 <list-index> 元素對映。
<?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>
<list name = "certificates" cascade="all">
<key column = "employee_id"/>
<list-index column = "idx"/>
<one-to-many class="Certificate"/>
</list>
<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 資料型別。
<list> 元素用於設定 Certificate 和 Employee 類之間的關係。我們在 <list> 元素中使用了 cascade 屬性來告訴 Hibernate 在與 Employee 物件同時持久化 Certificate 物件。name 屬性設定為父類中定義的 List 變數,在本例中為 certificates。
<key> 元素是 CERTIFICATE 表中儲存對父物件(即 EMPLOYEE 表)的外部索引鍵的列。
<list-index> 元素用於保留元素的位置並與集合表中的索引列對映。持久化列表的索引從零開始。例如,您可以在對映中將其更改為 <list-index base="1".../>。
<one-to-many> 元素表示一個 Employee 物件與多個 Certificate 物件相關聯,因此 Certificate 物件必須與其關聯的 Employee 父物件相關聯。您可以根據需要使用<one-to-one>、<many-to-one> 或<many-to-many> 元素。如果我們將此示例更改為使用多對多關係,則需要一個關聯表來對映父物件和子物件之間的關係。
建立應用程式類
最後,我們將建立具有 main() 方法的應用程式類以執行應用程式。我們將使用此應用程式儲存一些 Employee 的記錄以及它們的證書,然後我們將對這些記錄應用 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 */
ArrayList set1 = new ArrayList();
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 */
ArrayList set2 = new ArrayList();
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, ArrayList 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());
List 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 表中建立記錄。您可以看到,證書已按相反的順序排序。您可以嘗試更改對映檔案,只需設定sort="natural"並執行程式並比較結果。
$java ManageEmployee .......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ First Name: Manoj Last Name: Kumar Salary: 4000 Certificate: MCA Certificate: MBA Certificate: PMP First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA Certificate: BA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: MCA Certificate: MBA Certificate: PMP
如果檢查 EMPLOYEE 和 CERTIFICATE 表,它們應具有以下記錄:
mysql> select * from EMPLOYEE; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 51 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec) mysql> select * from CERTIFICATE; +----+------------------+------+-------------+ | id | certificate_name | idx | employee_id | +----+------------------+------+-------------+ | 6 | MCA | 0 | 51 | | 7 | MBA | 1 | 51 | | 8 | PMP | 2 | 51 | +----+------------------+------+-------------+ 3 rows in set (0.00 sec mysql>
或者,您可以對映 Java 陣列而不是列表。陣列對映與前面的示例幾乎相同,只是元素和屬性名稱不同(<array> 和 <array-index>)。但是,出於前面解釋的原因,Hibernate 應用程式很少使用陣列。