事件监听是JDK中常见的一种模式。 Hibernate中的事件监听机制可以对Session对象的动作进行监听,一旦发生了特殊的事件,Hibernate就会调用监听器类中的事件处理方法。在某些功能的设计中,既可以使用Hibernate的拦截器实现,也可以使用Hibernate的事件监听来实现。
  Hibernate 定义了多个事件涵盖了持久化过程中的不同生命同期,即Session对象中的第一个方法均分别对应事件。调用某个方法时就会触发相应的事件,并被预先设置的监听器收到及处理。
  Hibernate中事件监听器接口均在org.hibernate.event包中,事件与监听器接口对应关系如下:
  事件类型 对应的监听器接口 www.lefeng123.com
  auto-flush AutoFlushEventListener
  merge MergeEventListener
  delete DeleteEventListener
  persist PersistEventListener
  dirty-check DirtyCheckEventListener
  evict EvictEventListener
  flush FlushEventListener
  flush-entity FlushEntityEventListener
  load LoadEventListener
  load-collection LoadCollectionEventListener
  lock LockEventListener
  refresh RefreshEventListener
  replicate ReplicateEventListener
  save-update SaveUpdateEventListener
  pre-load PreLoadEventListener
  pre-update PreUpdateEventListener
  pre-delete PreDeleteEventListener
  pre-insert PreInsertEventListener
  post-load PostLoadEventListener
  post-update PostUpdateEventListener
  post-delete PostDeleteEventListener
  post-insert PostInsertEventListener
  注意:pre和post表示事件发生之前和之后。
  Hibernate 事件监听的使用方法如下:
  1、用户定制事件监听器首先需要与要处理事件相对应的接口,或者继承实现这个接口的类,然后通过 Hibernate的配置(hibernate.cfg.xml)配置事件监听器对象。如:
  public class LogPostLoadEventListener implements PostLoadEventListener{
  public void onPostLoad(PostLoadEvent event){
  ……
  …
  ……
  }
  }
  在Hibernate的配置文件中使用<listener>标签添加事件监听器功能:
  <mapping resource ="…" />
  <listener type="post-load" class="com.kkoolerter.Listener.LogPostLoadEventListener" />
  然而,也可以通过编程方式加载事件监听器对象 www.jamo123.com
  Configuration cfg = new Configuration();
  cfg.setListener("post-load",new LogPostLoadEventListener());
  cfg.configure();
  实现的代码如下:
  public interface Auditable {
  }
  public class AuditLog implements Serializable {
  private Integer id;
  private String entityName;
  private String entityId;
  private Date createTime;
  private String operationType;
  …
  }
  public class Product implements Serializable ,Auditable{
  private String id;
  private String name;
  private Double price;
  private String description;
  …
  }
  public enum OperationType {
  LoAD,CREATE,UPDATE,DELETE
  }
  配置文件如下:
  <hibernate-mapping>
  <class name="com.kkoolerter.hibernate.beans.AuditLog">
  <id name="id">
  <generator class="increment" />
  </id>
  <property name="entityName" />
  <property name="entityId" />
  <property name="createTime" />
  <property name="operationType" />
  </class>
  </hibernate-mapping>
  <hibernate-mapping>
  <class name="com.kkoolerter.hibernate.beans.Product">
  <id name="id">
  <generator class="uuid" />
  </id>
  <property name="name" />
  <property name="price" />
  <property name="description" />
  </class>
  </hibernate-mapping>
  <hibernate-configuration>
  <session-factory>
  <property name="dialect">
  org.hibernate.dialect.MySQLDialect
  </property>
  <property name="connection.url">
  jdbc:mysql://localhost:3306/hibernate_listener
  </property>
  <property name="connection.username">root</property>
  <property name="connection.password">123456</property>
  <property name="connection.driver_class">
  com.mysql.jdbc.Driver
  </property>
  <property name="show_sql">true</property>
  <mapping resource="com/kkoolerter/hibernate/beans/AuditLog.hbm.xml" />
  <mapping resource="com/kkoolerter/hibernate/beans/Product.hbm.xml" />
  <listener type="post-insert"
  class="com.kkoolerter.hibernate.listener.AuditLogEventListener" />
  <listener type="post-update"
  class="com.kkoolerter.hibernate.listener.AuditLogEventListener" />
  <listener type="post-delete"
  class="com.kkoolerter.hibernate.listener.AuditLogEventListener" />
  </session-factory>
  </hibernate-configuration>
  实现监听器的类 www.yztrans.com
  public class AuditLogEventListener implements PostUpdateEventListener,
  PostInsertEventListener, PostDeleteEventListener {
  private static final long serialVersionUID = 1L;
  public void onPostUpdate(PostUpdateEvent event) {
  if(event.getEntity() instanceof Auditable){
  String entityName = event.getEntity()。getClass()。getName();
  AuditLog log = new AuditLog();
  log.setEntityName(entityName);
  log.setOperationType(OperationType.UPDATE.toString());
  log.setEntityId(event.getId()。toString());
  log.setCreateTime(new Date());
  this.saveAuditLog(event.getSession(), log);
  }
  }
  public void onPostInsert(PostInsertEvent event) {
  if(event.getEntity() instanceof Auditable){
  String entityName = event.getEntity()。getClass()。getName();
  AuditLog log = new AuditLog();
  log.setEntityName(entityName);
  log.setOperationType(OperationType.CREATE.toString());
  log.setEntityId(event.getId()。toString());
  log.setCreateTime(new Date());
  this.saveAuditLog(event.getSession(), log);
  }
  }
  public void onPostDelete(PostDeleteEvent event) {
  if(event.getEntity() instanceof Auditable){
  String entityName = event.getEntity()。getClass()。getName();
  AuditLog log = new AuditLog();
  log.setEntityName(entityName);
  log.setOperationType(OperationType.DELETE.toString());
  log.setEntityId(event.getId()。toString());
  log.setCreateTime(new Date());
  this.saveAuditLog(event.getSession(), log);
  }
  }
  private void saveAuditLog(Session session,AuditLog log){
  Session logSession = session.getSessionFactory()。openSession();
  Transaction tx = logSession.beginTransaction();
  try {
  tx.begin();
  logSession.save(log);
  tx.commit();
  } catch (Exception e) {
  tx.rollback();
  e.printStackTrace();
  }
  }
  }
  测试代码:
  public class ListenerTest extends TestCase{
  public void testAdd(){
  Product p1 = new Product();
  p1.setDescription("Product 2");
  p1.setName("p2");
  p1.setPrice(3.3);
  Session session = HibernateUtils.getCurrentSession();
  Transaction tx = session.beginTransaction();
  session.save(p1);
  tx.commit();
  HibernateUtils.closeSession(session);
  }
  public void testUpdate(){
  Session session = HibernateUtils.getCurrentSession();
  Transaction tx = session.beginTransaction();
  Product p = (Product)session.get(Product.class,"402881ff278fefcf01278fefd0fe0001");
  //session.save(p1);
  p.setName("product 1");
  session.saveOrUpdate(p);
  tx.commit();
  HibernateUtils.closeSession(session);
  }
  public void testDelete(){
  Session session = HibernateUtils.getCurrentSession();
  Transaction tx = session.beginTransaction();
  Product p = (Product)session.get(Product.class,"402881ff278fefcf01278fefd0fe0001");
  //session.save(p1);
  //p.setName("product 1");
  session.delete(p);
  tx.commit();
  HibernateUtils.closeSession(session);
  }
  }

Hibernate 事件监听的更多相关文章

  1. 7_3.springboot2.x启动配置原理_3.事件监听机制

    事件监听机制配置在META-INF/spring.factories ApplicationContextInitializer SpringApplicationRunListenerioc容器中的 ...

  2. Java中用得比较顺手的事件监听

    第一次听说监听是三年前,做一个webGIS的项目,当时对Listener的印象就是个"监视器",监视着界面的一举一动,一有动静就触发对应的响应. 一.概述 通过对界面的某一或某些操 ...

  3. 4.JAVA之GUI编程事件监听机制

    事件监听机制的特点: 1.事件源 2.事件 3.监听器 4.事件处理 事件源:就是awt包或者swing包中的那些图形用户界面组件.(如:按钮) 事件:每一个事件源都有自己特点有的对应事件和共性事件. ...

  4. Node.js 教程 05 - EventEmitter(事件监听/发射器 )

    目录: 前言 Node.js事件驱动介绍 Node.js事件 注册并发射自定义Node.js事件 EventEmitter介绍 EventEmitter常用的API error事件 继承EventEm ...

  5. .NET事件监听机制的局限与扩展

    .NET中把“事件”看作一个基本的编程概念,并提供了非常优美的语法支持,对比如下C#和Java代码可以看出两种语言设计思想之间的差异. // C#someButton.Click += OnSomeB ...

  6. 让 select 的 option 标签支持事件监听(如复制操作)

    这标题,让option支持事件监听,应该不难的呀,有什么好讲的? 其实还是有的,默认在浏览器代码是无法直接对option标签进行操作的,不仅包括JS事件监听,还是CSS样式设置 查了一些资料,姑且认为 ...

  7. [JS]笔记12之事件机制--事件冒泡和捕获--事件监听--阻止事件传播

    -->事件冒泡和捕获-->事件监听-->阻止事件传播 一.事件冒泡和捕获 1.概念:当给子元素和父元素定义了相同的事件,比如都定义了onclick事件,点击子元素时,父元素的oncl ...

  8. [No00006A]Js的addEventListener()及attachEvent()区别分析【js中的事件监听】

    1.添加时间监听: Chrom中: addEventListener的使用方式: target.addEventListener(type, listener, useCapture); target ...

  9. java 事件监听 - 鼠标

    java 事件监听 - 鼠标 //事件监听 //鼠标事件监听 //鼠标事件监听有两个实现接口 //1.MouseListener 普通的鼠标操作 //2.MouseMotionListener 鼠标的 ...

随机推荐

  1. 数据结构(trie,启发式合并):HDU 5841 Alice and Bob

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABJEAAAE6CAIAAAApz1RvAAAgAElEQVR4nO3d3css1b3g8fyTdbHJbD

  2. runtime 如何实现 weak 属性

    出题者简介: 孙源(sunnyxx),目前就职于百度 整理者简介:陈奕龙(子循),目前就职于滴滴出行. 转载者:豆电雨(starain)微信:doudianyu 要实现 weak 属性,首先要搞清楚 ...

  3. IOS面试题(虽然我们很少用)

    其实我们会考很多C的基本知识,主要还是交流,这个题就是防止那些小白. 1.Objective-C中,与alloc语义相反的方法是dealloc还是release?与retain语义相反的方法是deal ...

  4. QML官方系列教程——QML Applications

    附网址:http://qt-project.org/doc/qt-5/qmlapplications.html 假设你对Qt的官方demo感兴趣,能够參考本博客的另一个系列Qt5官方demo解析集 每 ...

  5. win32程序中简单应用mfc

    今日写程序在win32中用CRect发现报错,突然想起来.要引入mfc库.想重新建立一个工程添加对mfc的支持.发现选项不能选.查资料后发现. 在win32程序中简单应用mfc库,只需要简单的引入&l ...

  6. java 连接数据库mysql的方法

    1.把那个文件配置好环境变量. 2.创建数据库,插入数据 注意的地方: (1)环境变量 classpath(可大写,也可以小写,可放在个人变量,也可以试系统变量) 里面的值 F:\mysql-conn ...

  7. 第一篇:数据工程师眼中的智能电网(Smart Grid)

    前言 想必第一次接触到智能电网这个概念的人,尤其是互联网从业者,都会顾名思义的将之理解为"智能的电网". 然而智能电网中的"智能"是广义上的智能,它就是指更好的 ...

  8. [转] Java中ArrayList类的用法

    1.什么是ArrayList ArrayList就是传说中的动态数组,用MSDN中的说法,就是Array的复杂版本,它提供了如下一些好处: 动态的增加和减少元素 实现了ICollection和ILis ...

  9. warning : json_decode(): option JSON_BIGINT_AS_STRING not implemented in xxx

    先来一段json_decode官方说明 mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, i ...

  10. python之路,Day24 常用设计模式学习

    python之路,Day24 常用设计模式学习   本节内容 设计模式介绍 设计模式分类 设计模式6大原则 1.设计模式介绍 设计模式(Design Patterns) --可复用面向对象软件的基础 ...