- Hibernate 教程
- Hibernate - 首頁
- ORM - 概述
- Hibernate - 概述
- Hibernate - 架構
- Hibernate - 環境
- Hibernate - 配置
- Hibernate - 會話(Sessions)
- Hibernate - 持久化類
- Hibernate - 對映檔案
- Hibernate - 對映型別
- Hibernate - 示例
- Hibernate - 物件關係對映(O/R Mappings)
- Hibernate - 級聯型別
- Hibernate - 註解
- Hibernate - 查詢語言
- Hibernate - Criteria 查詢
- Hibernate - 原生 SQL
- Hibernate - 快取
- Hibernate - 實體生命週期
- Hibernate - 批處理
- Hibernate - 攔截器
- Hibernate - ID 生成器
- Hibernate - 儲存圖片
- Hibernate - log4j 整合
- Hibernate - Spring 整合
- Hibernate - Struts 2 整合
- Hibernate - Web 應用
- 對映表示例
- Hibernate - 基於表繼承(Table Per Hiearchy)
- Hibernate - 基於具體類表(Table Per Concrete Class)
- Hibernate - 基於子類表(Table Per Subclass)
- Hibernate 有用資源
- Hibernate - 問答
- Hibernate - 快速指南
- Hibernate - 有用資源
- Hibernate - 討論
Hibernate - 排序對映(SortedMap 對映)
SortedMap 是類似於 Map 的 Java 集合,它以鍵值對的形式儲存元素,並對其鍵提供全序關係。對映中不允許重複元素。對映根據其鍵的自然順序排序,或者根據在排序對映建立時通常提供的 Comparator 排序。
SortedMap 在對映表中使用 <map> 元素進行對映,並且可以使用 java.util.TreeMap 初始化有序對映。
定義 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_type VARCHAR(40) default NULL, certificate_name VARCHAR(30) 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 SortedMap 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 SortedMap getCertificates() {
return certificates;
}
public void setCertificates( SortedMap certificates ) {
this.certificates = certificates;
}
}
我們需要定義另一個與 CERTIFICATE 表對應的 POJO 類,以便可以將證書物件儲存到 CERTIFICATE 表中並從中檢索。此類還應實現 Comparable 介面和 compareTo 方法,該方法將用於在對映檔案中設定 sort="natural" 時對 SortedMap 的鍵元素進行排序(參見下面的對映檔案)。
public class Certificate implements Comparable <String>{
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 int compareTo(String that){
final int BEFORE = -1;
final int AFTER = 1;
if (that == null) {
return BEFORE;
}
Comparable thisCertificate = this;
Comparable thatCertificate = that;
if(thisCertificate == null) {
return AFTER;
} else if(thatCertificate == null) {
return BEFORE;
} else {
return thisCertificate.compareTo(thatCertificate);
}
}
}
定義 Hibernate 對映檔案
讓我們開發我們的對映檔案,該檔案指示 Hibernate 如何將定義的類對映到資料庫表。<map> 元素將用於定義所用 Map 的規則。
<?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>
<map name = "certificates" cascade="all" sort="MyClass">
<key column = "employee_id"/>
<index column = "certificate_type" type = "string"/>
<one-to-many class="Certificate"/>
</map>
<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 資料型別。
<map> 元素用於設定 Certificate 和 Employee 類之間的關係。我們在 <map> 元素中使用了 cascade 屬性來告訴 Hibernate 在同時持久化 Employee 物件時持久化 Certificate 物件。name 屬性設定為父類中定義的 SortedMap 變數,在本例中為 certificates。sort 屬性可以設定為 natural 以進行自然排序,也可以設定為實現 java.util.Comparator 的自定義類。我們使用了實現 java.util.Comparator 的類 MyClass 來反轉在 Certificate 類中實現的排序順序。
<index> 元素用於表示鍵值對映對的關鍵部分。鍵將使用字串型別儲存在 certificate_type 列中。
<key> 元素是 CERTIFICATE 表中儲存到父物件(即 EMPLOYEE 表)的外部索引鍵的列。
<one-to-many> 元素指示一個 Employee 物件與多個 Certificate 物件相關聯,因此 Certificate 物件必須具有與其關聯的 Employee 父物件。您可以根據需要使用 <one-to-one>、<many-to-one> 或 <many-to-many> 元素。
如果我們使用 sort="natural" 設定,則不需要建立單獨的類,因為 Certificate 類已經實現了 Comparable 介面,Hibernate 將使用 Certificate 類中定義的 compareTo() 方法來比較 SortedMap 鍵。但是,我們在對映檔案中使用自定義比較器類 MyClass,因此我們必須根據我們的排序演算法建立此類。讓我們對對映中可用的鍵進行降序排序。
import java.util.Comparator;
public class MyClass implements Comparator <String>{
public int compare(String o1, String o2) {
final int BEFORE = -1;
final int AFTER = 1;
/* To reverse the sorting order, multiple by -1 */
if (o2 == null) {
return BEFORE * -1;
}
Comparable thisCertificate = o1;
Comparable thatCertificate = o2;
if(thisCertificate == null) {
return AFTER * 1;
} else if(thatCertificate == null) {
return BEFORE * -1;
} else {
return thisCertificate.compareTo(thatCertificate) * -1;
}
}
}
最後,我們將建立包含 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 */
TreeMap set1 = new TreeMap();
set1.put("ComputerScience", new Certificate("MCA"));
set1.put("BusinessManagement", new Certificate("MBA"));
set1.put("ProjectManagement", 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 */
TreeMap set2 = new TreeMap();
set2.put("ComputerScience", new Certificate("MCA"));
set2.put("BusinessManagement", new Certificate("MBA"));
/* 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, TreeMap 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());
SortedMap<String, Certificate> map = employee.getCertificates();
for(Map.Entry<String,Certificate> entry : map.entrySet()){
System.out.print("\tCertificate Type: " + entry.getKey());
System.out.println(", Name: " + (entry.getValue()).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 原始檔並編譯它。
建立如上所示的 MyClass.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 Type: ProjectManagement, Name: PMP Certificate Type: ComputerScience, Name: MCA Certificate Type: BusinessManagement, Name: MBA First Name: Dilip Last Name: Kumar Salary: 3000 Certificate Type: ComputerScience, Name: MCA Certificate Type: BusinessManagement, Name: MBA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate Type: ProjectManagement, Name: PMP Certificate Type: ComputerScience, Name: MCA Certificate Type: BusinessManagement, Name: MBA
如果您檢查 EMPLOYEE 和 CERTIFICATE 表,它們應該具有以下記錄:
mysql> select * from EMPLOYEE; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 74 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec) mysql> select * from CERTIFICATE; +----+--------------------+------------------+-------------+ | id | certificate_type | certificate_name | employee_id | +----+--------------------+------------------+-------------+ | 52 | BusinessManagement | MBA | 74 | | 53 | ComputerScience | MCA | 74 | | 54 | ProjectManagement | PMP | 74 | +----+--------------------+------------------+-------------+ 3 rows in set (0.00 sec) mysql>