百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Hibernate的拦截器(拦截器interceptor)

toyiye 2024-06-30 09:47 12 浏览 0 评论

拦截器

你已经学到,在 Hibernate 中,一个对象将被创建和保持。一旦对象已经被修改,它必须被保存到数据库里。这个过程持续直到下一次对象被需要,它将被从持久的存储中加载。

因此一个对象通过它生命周期中的不同阶段,并且 Interceptor 接口提供了在不同阶段能被调用来进行一些所需要的任务的方法。这些方法是从会话到应用程序的回调函数,允许应用程序检查或操作一个持续对象的属性,在它被保存,更新,删除或上传之前。以下是在 Interceptor 接口中可用的所有方法的列表。

Hibernate 拦截器给予了我们一个对象如何应用到应用程序和数据库的总控制。

如何使用拦截器?

为了创建一个拦截器你可以直接实现 Interceptor 类或者继承 EmptyInterceptor 类。以下是简单的使用 Hibernate 拦截器功能的步骤。

创建拦截器

我们将在例子中继承 EmptyInterceptor,当 Employee 对象被创建和更新时拦截器的方法将自动被调用。你可以根据你的需求实现更多的方法。

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

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

创建数据库表

第二步将是在你的数据库中创建表。一张表对应每个你提供持久性的对象。考虑以上的对象需要被存储和检索到以下的 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)
);

创建 Mapping 配置文件

这个步骤是来创建一个指导 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>

创建 Application 类

最后,我们将用 main() 创建 application 类来运行应用程序。这里应该注意当创建 session 对象时我们使用 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();
 /* 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(); 
 }
 }
}

编译和执行

这里是编译和运行上面提及的应用程序的步骤。确保你已经在处理编译和执行前正确设置了 PATH 和 CLASSPATH。

  • 创建在 configuration 章节中解释的 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
postFlush

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

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码