Hibernate - 示例



現在讓我們來看一個例子,瞭解如何使用 Hibernate 在獨立應用程式中提供 Java 永續性。我們將逐步介紹使用 Hibernate 技術建立 Java 應用程式的不同步驟。

建立 POJO 類

建立應用程式的第一步是構建 Java POJO 類(或多個類),這取決於將持久化到資料庫的應用程式。讓我們考慮一下我們的Employee類,它具有getXXXsetXXX方法,使其符合 JavaBeans 規範。

POJO(普通舊 Java 物件)是一個 Java 物件,它沒有擴充套件或實現 EJB 框架分別要求的某些特殊類和介面。所有普通的 Java 物件都是 POJO。

當您設計一個類由 Hibernate 持久化時,務必提供符合 JavaBeans 規範的程式碼以及一個屬性,該屬性將充當索引,例如Employee類中的id屬性。

public class Employee {
   private int id;
   private String firstName; 
   private String lastName;   
   private int salary;  

   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;
   }
}

建立資料庫表

第二步是在您的資料庫中建立表。對於每個要提供永續性的物件,將對應一個表。考慮一下上述需要儲存和檢索到以下 RDBMS 表中的物件:

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)
);

建立對映配置檔案

此步驟是建立一個對映檔案,該檔案指示 Hibernate 如何將定義的類對映到資料庫表。

<?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>
      
      <property name = "firstName" column = "first_name" type = "string"/>
      <property name = "lastName" column = "last_name" type = "string"/>
      <property name = "salary" column = "salary" type = "int"/>
      
   </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 資料型別。

還有其他可用於對映文件的屬性和元素,在討論其他與 Hibernate 相關的主題時,我將嘗試儘可能多地介紹。

建立應用程式類

最後,我們將建立包含 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.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();

      /* 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(fname, lname, 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(); 
      }
   }
}

編譯和執行

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

  • 按照配置章節中的說明建立 hibernate.cfg.xml 配置檔案。

  • 建立如上所示的 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>
廣告
© . All rights reserved.