鍍金池/ 教程/ Java/ 攔截器
例子
注釋
映射類型
ORM 概覽
環(huán)境
標(biāo)準(zhǔn)查詢
原生 SQL
持久化類
查詢語言
配置
批處理
緩存
架構(gòu)
會話
映射文件
O/R 映射
簡介
攔截器

攔截器

你已經(jīng)學(xué)到,在 Hibernate 中,一個對象將被創(chuàng)建和保持。一旦對象已經(jīng)被修改,它必須被保存到數(shù)據(jù)庫里。這個過程持續(xù)直到下一次對象被需要,它將被從持久的存儲中加載。

因此一個對象通過它生命周期中的不同階段,并且 Interceptor 接口提供了在不同階段能被調(diào)用來進行一些所需要的任務(wù)的方法。這些方法是從會話到應(yīng)用程序的回調(diào)函數(shù),允許應(yīng)用程序檢查或操作一個持續(xù)對象的屬性,在它被保存,更新,刪除或上傳之前。以下是在 Interceptor 接口中可用的所有方法的列表。

S.N. 方法和描述
1 findDirty()
這個方法在當(dāng) flush() 方法在一個 Session 對象上被調(diào)用時被調(diào)用。
2 instantiate()
這個方法在一個持續(xù)的類被實例化時被調(diào)用。
3 isUnsaved()
這個方法在當(dāng)一個對象被傳到 saveOrUpdate() 方法時被調(diào)用。
4 onDelete()
這個方法在一個對象被刪除前被調(diào)用。
5 onFlushDirty()
這個方法在當(dāng) Hibernate 探測到一個對象在一次 flush(例如,更新操作)中是臟的(例如,被修改)時被調(diào)用。
6 onLoad()
這個方法在一個對象被初始化之前被調(diào)用。
7 onSave()
這個方法在一個對象被保存前被調(diào)用。
8 postFlush()
這個方法在一次 flush 已經(jīng)發(fā)生并且一個對象已經(jīng)在內(nèi)存中被更新后被調(diào)用。
9 preFlush()
這個方法在一次 flush 前被調(diào)用。

Hibernate 攔截器給予了我們一個對象如何應(yīng)用到應(yīng)用程序和數(shù)據(jù)庫的總控制。

如何使用攔截器?

為了創(chuàng)建一個攔截器你可以直接實現(xiàn) Interceptor 類或者繼承 EmptyInterceptor 類。以下是簡單的使用 Hibernate 攔截器功能的步驟。

創(chuàng)建攔截器

我們將在例子中繼承 EmptyInterceptor,當(dāng) Employee 對象被創(chuàng)建和更新時攔截器的方法將自動被調(diào)用。你可以根據(jù)你的需求實現(xiàn)更多的方法。

import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;

public class MyInterceptor extends EmptyInterceptor {
   private int updates;
   private int creates;
   private int loads;

   public void onDelete(Object entity,
                     Serializable id,
                     Object[] state,
                     String[] propertyNames,
                     Type[] types) {
       // do nothing
   }

   // This method is called when Employee object gets updated.
   public boolean onFlushDirty(Object entity,
                     Serializable id,
                     Object[] currentState,
                     Object[] previousState,
                     String[] propertyNames,
                     Type[] types) {
       if ( entity instanceof Employee ) {
          System.out.println("Update Operation");
          return true; 
       }
       return false;
   }
   public boolean onLoad(Object entity,
                    Serializable id,
                    Object[] state,
                    String[] propertyNames,
                    Type[] types) {
       // do nothing
       return true;
   }
   // This method is called when Employee object gets created.
   public boolean onSave(Object entity,
                    Serializable id,
                    Object[] state,
                    String[] propertyNames,
                    Type[] types) {
       if ( entity instanceof Employee ) {
          System.out.println("Create Operation");
          return true; 
       }
       return false;
   }
   //called before commit into database
   public void preFlush(Iterator iterator) {
      System.out.println("preFlush");
   }
   //called after committed into database
   public void postFlush(Iterator iterator) {
      System.out.println("postFlush");
   }
}

創(chuàng)建 POJO 類

現(xiàn)在讓我們稍微修改我們的第一個例子,我們使用 EMPLOYEE 表單和 Employee 類:

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ù)庫表

第二步將是在你的數(shù)據(jù)庫中創(chuàng)建表。一張表對應(yīng)每個你提供持久性的對象??紤]以上的對象需要被存儲和檢索到以下的 RDBM 表中:

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)建 Mapping 配置文件

這個步驟是來創(chuàng)建一個指導(dǎo) Hibernate 如何將定義的類或者多個類映射到數(shù)據(jù)庫表單中的映射文件。

<?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>

創(chuàng)建 Application 類

最后,我們將用 main() 創(chuàng)建 application 類來運行應(yīng)用程序。這里應(yīng)該注意當(dāng)創(chuàng)建 session 對象時我們使用 Interceptor 類作為參數(shù)。

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( new MyInterceptor() );
      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( new MyInterceptor() );
      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( new MyInterceptor() );
      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( new MyInterceptor() );
      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īng)用程序的步驟。確保你已經(jīng)在處理編譯和執(zhí)行前正確設(shè)置了 PATH 和 CLASSPATH。

  • 創(chuàng)建在 configuration 章節(jié)中解釋的 hibernate.cfg.xml 配置文件。
  • 創(chuàng)建如上所示的 Employee.hbm.xml 映射文件。
  • 創(chuàng)建如上所示的 Employee.java 源文件并編譯。
  • 創(chuàng)建如上所示的 MyInterceptor.java 源文件并編譯。
  • 創(chuàng)建如上所示的 ManageEmployee.java 源文件并編譯。
  • 執(zhí)行 ManageEmployee 來運行程序。

你將得到以下結(jié)果,而且記錄將在 EMPLOYEE 表單中被創(chuàng)建。

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

Create Operation
preFlush
postFlush
Create Operation
preFlush
postFlush
Create Operation
preFlush
postFlush
First Name: Zara  Last Name: Ali  Salary: 1000
First Name: Daisy  Last Name: Das  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000
preFlush
postFlush
preFlush
Update Operation
postFlush
preFlush
postFlush
First Name: Zara  Last Name: Ali  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000
preFlush
postFlush

如果你檢查你的 EMPLOYEE 表單,它應(yīng)該有如下結(jié)果:

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>
下一篇:緩存