Hibernate 例子

2019-05-11 18:22 更新

例子

讓我們看一個(gè)獨(dú)立應(yīng)用程序利用 Hibernate 提供 Java 持久性的例子。我們將通過(guò)不同的步驟使用 Hibernate 技術(shù)創(chuàng)建 Java 應(yīng)用程序。

創(chuàng)建 POJO 類(lèi)

創(chuàng)建應(yīng)用程序的第一步就是建立 Java 的 POJO 類(lèi)或者其它類(lèi),這取決于即將要存放在數(shù)據(jù)庫(kù)中的應(yīng)用程序。我們可以考慮一下讓我們的 Employee 類(lèi)使用 getXXXsetXXX 方法從而使它們變成符合 JavaBeans 的類(lèi)。

POJO (Plain Old Java Object) 是 Java 的一個(gè)對(duì)象,這種對(duì)象不會(huì)擴(kuò)展或者執(zhí)行一些特殊的類(lèi)并且它的接口都是分別在 EJB 框架的要求下的。所有正常的 Java 對(duì)象都是 POJO。

當(dāng)你設(shè)計(jì)一個(gè)存放在 Hibernate 中的類(lèi)時(shí),最重要的是提供支持 JavaBeans 的代碼和在 Employee 類(lèi)中像 id 屬性一樣可以當(dāng)做索引的屬性。

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

創(chuàng)建數(shù)據(jù)庫(kù)表

第二步就是在你的數(shù)據(jù)庫(kù)中創(chuàng)建表格。每一個(gè)你所愿意提供長(zhǎng)期留存的對(duì)象都會(huì)有一個(gè)對(duì)應(yīng)的表。上述的對(duì)象需要在下列的 RDBMS 表中存儲(chǔ)和被檢索到:

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

創(chuàng)建映射配置文件

這一步是創(chuàng)建一個(gè)映射文件從而指導(dǎo) Hibernate 如何對(duì)數(shù)據(jù)庫(kù)的表映射定義的類(lèi)。

<?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的格式保存在一個(gè)文件中。我們將映射文檔保存在 Employee.hbm.xml文件中。下面讓我們看看映射文檔相關(guān)的一些小細(xì)節(jié):

  • 映射文檔是一個(gè) XML 格式的文檔,它擁有<hibernate-mapping>作為根元素,這個(gè)元素包含了所有的 <class>元素。
  • <class> 元素被用來(lái)定義從 Java 類(lèi)到數(shù)據(jù)庫(kù)表的特定的映射。Java 類(lèi)的名稱(chēng)是特定的,它使用的是類(lèi)元素的 name 屬性,數(shù)據(jù)庫(kù)表的名稱(chēng)也是特定的,它使用的是 table 屬性。
  • <meta> 元素是一個(gè)可選元素,它可以用來(lái)創(chuàng)建類(lèi)的描述。
  • <id> 元素向數(shù)據(jù)庫(kù)的主要關(guān)鍵字表映射類(lèi)中的特定的 ID 屬性。id 元素的 name 屬性涉及到了類(lèi)中的屬性同時(shí) column 屬性涉及到了數(shù)據(jù)庫(kù)表中的列。type 屬性掌握了 hibernate 的映射類(lèi)型,這種映射類(lèi)型將會(huì)從 Java 轉(zhuǎn)到 SQL 數(shù)據(jù)類(lèi)型。
  • id 元素中的 <generator>元素是用來(lái)自動(dòng)產(chǎn)生主要關(guān)鍵字的值的。將 generator 元素的 class 屬性設(shè)置成 native 從而使 Hibernate 運(yùn)用 identity, sequence 或者 hilo 算法依靠基礎(chǔ)數(shù)據(jù)庫(kù)的性能來(lái)創(chuàng)建主要關(guān)鍵字。
  • <property> 元素是用來(lái)映射一個(gè) Java 類(lèi)的屬性到數(shù)據(jù)庫(kù)的表中的列中。這個(gè)元素的 name 屬性涉及到類(lèi)中的屬性,column 屬性涉及到數(shù)據(jù)表中的列。type 屬性控制 Hibernate 的映射類(lèi)型,這種映射類(lèi)型將會(huì)從 Java 轉(zhuǎn)到 SQL 數(shù)據(jù)類(lèi)型。

映射文檔中還有許多其它的屬性和元素,在探討其它的 Hibernate 相關(guān)的話題時(shí)我將會(huì)詳細(xì)進(jìn)行講解。

創(chuàng)建應(yīng)用程序類(lèi)

最后,我們將要使用 main() 方法創(chuàng)建應(yīng)用程序類(lèi)來(lái)運(yùn)行應(yīng)用程序。我們將用這個(gè)程序來(lái)保存一些 Employee 的記錄,然后我們將在這些記錄上應(yīng)用 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(); 
      }
   }
}

編譯和執(zhí)行

下面是編譯和運(yùn)行上述提到的應(yīng)用程序的步驟。在編譯和執(zhí)行應(yīng)用程序之前確保你已經(jīng)設(shè)置好了 PATH 和 CLASSPATH。

  • 創(chuàng)建設(shè)置章節(jié)中所講的 hibernate.cfg.xml 配置文件。
  • 創(chuàng)建上文所述的 Employee.hbm.xml 映射文件。
  • 創(chuàng)建上文所述的 Employee.java 源文件并且進(jìn)行編譯。
  • 創(chuàng)建上文所述的 ManageEmployee.java 源文件并且進(jìn)行編譯。
  • 執(zhí)行二進(jìn)制的 ManageEmployee 來(lái)運(yùn)行程序。

你將會(huì)得到如下結(jié)果,記錄將會(huì)在 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 表,它將會(huì)有如下記錄:

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>
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)