zoukankan      html  css  js  c++  java
  • Hibernate 事件监听

      事件监听是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);
      }
      }

  • 相关阅读:
    Idea导入tomcat源码
    SpringBoot学习 (一) Eclipse中创建新的SpringBoot项目
    Zookeeper客户端Curator使用详解
    解决老是提示找不到Mapper文件无法执行定义的方法问题!
    人工智能、机器学习、深度学习三者之间的关系
    java5增加对https的支持
    Spring静态注入的三种方式
    Thrift入门及Java实例演示【转】
    activeMQ 学习
    python中 import 和from ... import 的区别
  • 原文地址:https://www.cnblogs.com/haosola/p/3640047.html
Copyright © 2011-2022 走看看