- 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 - 表繼承策略(Table Per Hierarchy)
- Hibernate - 表對應具體類策略(Table Per Concrete Class)
- Hibernate - 表對應子類策略(Table Per Subclass)
- Hibernate 有用資源
- Hibernate - 問答
- Hibernate - 快速指南
- Hibernate - 有用資源
- Hibernate - 討論
Hibernate - Bag 對映
Bag 是一個 Java 集合,它儲存元素時不關心順序,但允許列表中存在重複元素。Bag 是列表中物件的隨機分組。
集合在對映表中使用 <bag> 元素對映,並使用 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, 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 Collection 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 Collection getCertificates() {
return certificates;
}
public void setCertificates( Collection 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 如何將定義的類對映到資料庫表。<bag> 元素將用於定義所用集合的規則。
<?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>
<bag name = "certificates" cascade="all">
<key column = "employee_id"/>
<one-to-many class="Certificate"/>
</bag>
<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 資料型別。
<bag> 元素用於設定 Certificate 和 Employee 類之間的關係。我們在 <bag> 元素中使用cascade屬性來告訴 Hibernate 在同時持久化 Employee 物件時持久化 Certificate 物件。name屬性設定為父類中定義的Collection變數,在本例中為certificates。
<key> 元素是 CERTIFICATE 表中儲存對父物件(即 EMPLOYEE 表)的外部索引鍵的列。
<one-to-many> 元素表示一個 Employee 物件與多個 Certificate 物件相關聯,因此 Certificate 物件必須與其關聯的 Employee 父物件相關聯。您可以根據需要使用<one-to-one>、<many-to-one>或<many-to-many>元素。
建立應用程式類
最後,我們將建立帶有 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 */
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());
Collection 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 | +----+------------+-----------+--------+ | 53 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec) mysql> select * from CERTIFICATE; +----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 11 | MCA | 53 | | 12 | MBA | 53 | | 13 | PMP | 53 | +----+------------------+-------------+ 3 rows in set (0.00 sec) mysql>