Hibernate - 註解



到目前為止,您已經瞭解了 Hibernate 如何使用 XML 對映檔案將資料從 POJO 轉換為資料庫表,反之亦然。Hibernate 註解是定義對映的最新方法,無需使用 XML 檔案。您可以將註解與 XML 對映元資料一起使用,或者作為 XML 對映元資料的替代。

Hibernate 註解是提供物件和關係表對映元資料的一種強大方法。所有元資料都與程式碼一起打包到 POJO Java 檔案中,這有助於使用者在開發過程中同時理解表結構和 POJO。

如果您打算使您的應用程式可移植到其他符合 EJB 3 的 ORM 應用程式,則必須使用註解來表示對映資訊,但如果您仍希望獲得更大的靈活性,則應使用基於 XML 的對映。

Hibernate 註解的環境設定

首先,您必須確保您正在使用 JDK 5.0,否則您需要將 JDK 升級到 JDK 5.0 以利用對註解的原生支援。

其次,您需要安裝 Hibernate 3.x 註解分發包,可從 sourceforge 獲取:(下載 Hibernate 註解)並將 hibernate-annotations.jar、lib/hibernate-comons-annotations.jarlib/ejb3-persistence.jar 從 Hibernate 註解分發版複製到您的 CLASSPATH 中。

帶註解的類示例

如上所述,在使用 Hibernate 註解時,所有元資料都與程式碼一起打包到 POJO Java 檔案中,這有助於使用者在開發過程中同時理解表結構和 POJO。

假設我們將使用以下 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)
);

以下是使用註解將 Employee 類對映到定義的 EMPLOYEE 表的對映 -

import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
   @Id @GeneratedValue
   @Column(name = "id")
   private int id;

   @Column(name = "first_name")
   private String firstName;

   @Column(name = "last_name")
   private String lastName;

   @Column(name = "salary")
   private int salary;  

   public Employee() {}
   
   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;
   }
}

Hibernate 檢測到 @Id 註解位於一個欄位上,並假設它應該在執行時透過欄位直接訪問物件的屬性。如果您將 @Id 註解放在 getId() 方法上,則預設情況下,您將啟用透過 getter 和 setter 方法訪問屬性。因此,所有其他註解也放置在欄位或 getter 方法上,遵循所選策略。

以下部分將解釋在上述類中使用的註解。

@Entity 註解

EJB 3 標準註解包含在 javax.persistence 包中,因此我們將此包作為第一步匯入。其次,我們將 @Entity 註解用於 Employee 類,這將此類標記為實體 Bean,因此它必須具有一個可見範圍至少為受保護的無引數建構函式。

@Table 註解

@Table 註解允許您指定將用於在資料庫中持久化實體的表的詳細資訊。

@Table 註解提供了四個屬性,允許您覆蓋表名稱、其目錄和模式,並對錶中的列強制實施唯一約束。目前,我們只使用表名,即 EMPLOYEE。

@Id 和 @GeneratedValue 註解

每個實體 Bean 將具有一個主鍵,您可以在類上使用 @Id 註解對其進行註釋。主鍵可以是單個欄位或多個欄位的組合,具體取決於您的表結構。

預設情況下,@Id 註解將自動確定要使用的最合適的 primary key 生成策略,但您可以透過應用 @GeneratedValue 註解來覆蓋此策略,該註解採用兩個引數 strategygenerator,我在這裡不討論它們,因此讓我們只使用預設鍵生成策略。讓 Hibernate 確定要使用哪個生成器型別可以使您的程式碼在不同的資料庫之間可移植。

@Column 註解

@Column 註解用於指定欄位或屬性將對映到的列的詳細資訊。您可以將列註解與以下最常用的屬性一起使用 -

  • name 屬性允許顯式指定列的名稱。

  • length 屬性允許指定用於對映值的列的大小,特別是對於 String 值。

  • nullable 屬性允許在生成模式時將列標記為 NOT NULL。

  • unique 屬性允許將列標記為僅包含唯一值。

建立應用程式類

最後,我們將建立包含 main() 方法的應用程式類以執行應用程式。我們將使用此應用程式儲存一些 Employee 記錄,然後我們將對這些記錄應用 CRUD 操作。

import java.util.List; 
import java.util.Date;
import java.util.Iterator; 
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
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 AnnotationConfiguration().
                   configure().
                   //addPackage("com.xyz") //add package if used.
                   addAnnotatedClass(Employee.class).
                   buildSessionFactory();
      } catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      
      ManageEmployee ME = new ManageEmployee();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);

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

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

      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);

      /* List down new list of the employees */
      ME.listEmployees();
   }
   
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      
      try {
         tx = session.beginTransaction();
         Employee employee = new Employee();
         employee.setFirstName(fname);
         employee.setLastName(lname);
         employee.setSalary(salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      } catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      } finally {
         session.close(); 
      }
      return employeeID;
   }
   
   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      
      try {
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list(); 
         for (Iterator iterator = employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next(); 
            System.out.print("First Name: " + employee.getFirstName()); 
            System.out.print("  Last Name: " + employee.getLastName()); 
            System.out.println("  Salary: " + employee.getSalary()); 
         }
         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(); 
      }
   }
}

資料庫配置

現在讓我們建立 hibernate.cfg.xml 配置檔案以定義與資料庫相關的引數。

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   
      <property name = "hibernate.dialect">
         org.hibernate.dialect.MySQLDialect
      </property>
   
      <property name = "hibernate.connection.driver_class">
         com.mysql.jdbc.Driver
      </property>

      <!-- Assume students is the database name -->
   
      <property name = "hibernate.connection.url">
         jdbc:mysql:///test
      </property>
   
      <property name = "hibernate.connection.username">
         root
      </property>
   
      <property name = "hibernate.connection.password">
         cohondob
      </property>

   </session-factory>
</hibernate-configuration>

編譯和執行

以下是編譯和執行上述應用程式的步驟。在繼續進行編譯和執行之前,請確保您已正確設定 PATH 和 CLASSPATH。

  • 從路徑中刪除 Employee.hbm.xml 對映檔案。

  • 建立如上所示的 Employee.java 原始檔並編譯它。

  • 建立如上所示的 ManageEmployee.java 原始檔並編譯它。

  • 執行 ManageEmployee 二進位制檔案以執行程式。

您將獲得以下結果,並且記錄將建立在 EMPLOYEE 表中。

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

First Name: Zara  Last Name: Ali  Salary: 1000
First Name: Daisy  Last Name: Das  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000
First Name: Zara  Last Name: Ali  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000

如果您檢查 EMPLOYEE 表,它應該包含以下記錄 -

mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 29 | Zara       | Ali       |   5000 |
| 31 | John       | Paul      |  10000 |
+----+------------+-----------+--------+
2 rows in set (0.00 sec

mysql>
廣告