- 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 - 排序集合對映
一個SortedSet是Java集合,它不包含任何重複元素,並且元素使用其自然順序或提供的比較器進行排序。
SortedSet 在對映表中使用 <set> 元素進行對映,並使用 java.util.TreeSet 初始化。sort 屬性可以設定為比較器或自然排序。如果我們使用自然排序,則其迭代器將按升序元素順序遍歷集合。
定義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表相關的物件,並在SortedSet變數中包含一系列證書。
import java.util.*;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
private SortedSet 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 SortedSet getCertificates() {
return certificates;
}
public void setCertificates( SortedSet certificates ) {
this.certificates = certificates;
}
}
現在讓我們定義另一個與CERTIFICATE表對應的POJO類,以便可以將證書物件儲存和檢索到CERTIFICATE表中。此類還應實現Comparable介面和compareTo方法,這將在您在對映檔案中設定sort="natural"時用於排序元素(請參見下面的對映檔案):
public class Certificate implements Comparable <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 int compareTo(Certificate that){
final int BEFORE = -1;
final int AFTER = 1;
if (that == null) {
return BEFORE;
}
Comparable thisCertificate = this.getName();
Comparable thatCertificate = that.getName();
if(thisCertificate == null) {
return AFTER;
} else if(thatCertificate == null) {
return BEFORE;
} else {
return thisCertificate.compareTo(thatCertificate);
}
}
}
定義Hibernate對映檔案
讓我們開發我們的對映檔案,該檔案指示Hibernate如何將定義的類對映到資料庫表。<set> 元素將用於定義所使用的 SortedSet 集合的規則。
<?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" sort="MyClass">
<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同時持久化Certificate物件和Employee物件。name屬性設定為父類中定義的SortedSet變數,在本例中為certificates。sort 屬性可以設定為natural以進行自然排序,也可以設定為實現java.util.Comparator的自定義類。我們使用了實現 java.util.Comparator 的類MyClass來反轉在Certificate類中實現的排序順序。
<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()方法來比較證書名稱。但是我們在對映檔案中使用自定義比較器類MyClass,因此我們必須根據我們的排序演算法建立此類。讓我們在這個類中使用這個類進行降序排序。
import java.util.Comparator;
public class MyClass implements Comparator<Certificate>{
public int compare(Certificate o1, Certificate 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.getName();
Comparable thatCertificate = o2.getName();
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 */
TreeSet set1 = new TreeSet();
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 */
TreeSet set2 = new TreeSet();
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, SortedSet 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());
SortedSet 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原始檔並編譯它。
建立如上所示的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: PMP Certificate: MCA Certificate: MBA First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA Certificate: BA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: PMP Certificate: MCA Certificate: MBA
如果您檢查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>