教程 > hibernate 教程 > 阅读:47

hibernate 拦截器——迹忆客-ag捕鱼王app官网

正如我们所了解的,在 hibernate 中,将创建并保留一个对象。 一旦对象被改变,它必须被保存回数据库。 这个过程一直持续到下一次需要该对象时,它将从持久存储中加载。

因此,一个对象在其生命周期中会经历不同的阶段,interceptor interface 提供了方法,可以在不同的阶段调用这些方法来执行一些需要的任务。 这些方法是从会话到应用程序的回调,允许应用程序在保存、更新、删除或加载持久对象之前检查和/或操作持久对象的属性。 以下是 interceptor 接口中所有可用方法的列表。

序号 方法 描述
1 finddirty() 当对 session 对象调用 flush() 方法时,将调用此方法。
2 instantiate() 该方法在持久化类被实例化时被调用。
3 isunsaved() 当一个对象被传递给 saveorupdate() 方法时,将调用此方法
4 ondelete() 在删除对象之前调用此方法。
5 onflushdirty() 当 hibernate 在刷新(即更新操作)期间检测到对象是脏的(即已被更改)时,将调用此方法。
6 onload() 在初始化对象之前调用此方法。
7 onsave() 在保存对象之前调用此方法。
8 postflush() 在发生刷新并且对象已在内存中更新后调用此方法。
9 preflush() 此方法在刷新之前调用。

hibernate interceptor 让我们可以完全控制对象在应用程序和数据库中的外观。


如何使用拦截器?

要构建拦截器,我们可以直接实现 interceptor 接口或继承 emptyinterceptor 类。 以下将是使用 hibernate interceptor 功能的简单步骤。

创建拦截器

我们将在示例中j继承 emptyinterceptor,其中在创建和更新 employee 对象时将自动调用 interceptor 的方法。 我们可以根据自己的要求实现更多方法。

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
   }
   // 当 employee 对象更新时调用此方法。
   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;
   }
   
   // 此方法在创建 employee 对象时调用。
   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;
   }
   
   // 在提交到数据库之前调用
   public void preflush(iterator iterator) {
      system.out.println("preflush");
   }
   
   // 提交到数据库后调用
   public void postflush(iterator iterator) {
      system.out.println("postflush");
   }
}

创建 pojo 类

现在,让我们稍微修改一下我们使用 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;
   }
}

创建数据库表

第二步是在我们的数据库中创建表。 每个对象都会有一个表,我们愿意提供持久性。 考虑上面解释的对象,需要存储和检索到以下 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——如何将定义的一个或多个类映射到数据库表。


 

   
      
      
         this class contains the employee detail. 
      
      
      
         
      
      
      
      
      
      
   

创建应用程序类

最后,我们将使用 main() 方法创建我们的应用程序类来运行应用程序。 在这里,应该注意的是,在创建会话对象时,我们使用了我们的 interceptor 类作为参数。

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();
      /* 在数据库中添加一些员工记录 */
      integer empid1 = me.addemployee("zara", "ali", 1000);
      integer empid2 = me.addemployee("daisy", "das", 5000);
      integer empid3 = me.addemployee("john", "paul", 10000);
      /* 列出所有员工记录 */
      me.listemployees();
      /* 更新员工记录 */
      me.updateemployee(empid1, 5000);
      /* 从数据库中删除员工 */
      me.deleteemployee(empid2);
      /* 列出新的员工名单 */
      me.listemployees();
   }
   
   /* 在数据库中创建员工的方法 */
   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;
   }
   
   /* 读取所有员工的方法 */
   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(); 
      }
   }
   
   /* 更新员工工资的方法 */
   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(); 
      }
   }
   
   /* 从记录中删除员工的方法 */
   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(); 
      }
   }
}

编译和执行

以下是编译和运行上述应用程序的步骤。 在继续编译和执行之前,请确保已正确设置 path 和 classpath。

  • 按照配置章节中的说明创建 hibernate.cfg.xml 配置文件。
  • 如上所示创建employee.hbm.xml 映射文件。
  • 如上所示创建employee.java 源文件并编译它。
  • 如上所示创建 myinterceptor.java 源文件并编译它。
  • 如上所示创建 manageemployee.java 源文件并编译它。
  • 执行 manageemployee 二进制文件来运行程序。

我们将获得以下结果,并且将在 employee 表中创建记录。

$ 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
postflus

如果检查 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

查看笔记

扫码一下
查看教程更方便
网站地图