Hibernate - 對映



Map 是一個 Java 集合,它以鍵值對的形式儲存元素,並且不允許列表中出現重複元素。Map 介面提供三個集合檢視,允許將對映的內容視為鍵集、值集合或鍵值對映集。

Map 在對映表中使用 <map> 元素進行對映,並且可以使用 java.util.HashMap 初始化無序對映。

定義 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 Map 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 Map getCertificates() {
      return certificates;
   }
   
   public void setCertificates( Map 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 如何將定義的類對映到資料庫表。<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">
         <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、sequencehilo演算法來建立主鍵。

  • <property> 元素用於將 Java 類屬性對映到資料庫表中的列。元素的name屬性引用類中的屬性,column屬性引用資料庫表中的列。type屬性儲存 Hibernate 對映型別,這些對映型別將從 Java 轉換為 SQL 資料型別。

  • <map> 元素用於設定 Certificate 和 Employee 類之間的關係。我們在 <map> 元素中使用了cascade屬性來告訴 Hibernate 在同時持久化 Employee 物件時也持久化 Certificate 物件。name屬性設定為父類中定義的Map變數,在我們的例子中是certificates

  • <index> 元素用於表示鍵值對映對的關鍵部分。鍵將使用字串型別儲存在 certificate_type 列中。

  • <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  */
      HashMap set = new HashMap();
      set.put("ComputerScience", new Certificate("MCA"));
      set.put("BusinessManagement", new Certificate("MBA"));
      set.put("ProjectManagement", new Certificate("PMP"));
     
      /* Add employee records in the database */
      Integer empID = ME.addEmployee("Manoj", "Kumar", 4000, set);

      /* List down all the employees */
      ME.listEmployees();

      /* Update employee's salary records */
      ME.updateEmployee(empID, 5000);

      /* 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, HashMap 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());
            Map ec = employee.getCertificates();
            System.out.println("Certificate: " + 
              (((Certificate)ec.get("ComputerScience")).getName()));
            System.out.println("Certificate: " + 
              (((Certificate)ec.get("BusinessManagement")).getName()));
            System.out.println("Certificate: " + 
              (((Certificate)ec.get("ProjectManagement")).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 表中建立記錄。

$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........

First Name: Manoj  Last Name: Kumar  Salary: 4000
Certificate: MCA
Certificate: MBA
Certificate: PMP
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 |
+----+------------+-----------+--------+
| 60 | Manoj      | Kumar     |   5000 |
+----+------------+-----------+--------+
1 row in set (0.00 sec)

mysql>select * from CERTIFICATE;
+----+--------------------+------------------+-------------+
| id | certificate_type   | certificate_name | employee_id |
+----+--------------------+------------------+-------------+
| 16 | ProjectManagement  | PMP              |          60 |
| 17 | BusinessManagement | MBA              |          60 |
| 18 | ComputerScience    | MCA              |          60 |
+----+--------------------+------------------+-------------+
3 rows in set (0.00 sec)

mysql>
hibernate_or_mappings.htm
廣告

© . All rights reserved.