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);
}
}
Hibernate 事件监听的更多相关文章
- 7_3.springboot2.x启动配置原理_3.事件监听机制
事件监听机制配置在META-INF/spring.factories ApplicationContextInitializer SpringApplicationRunListenerioc容器中的 ...
- Java中用得比较顺手的事件监听
第一次听说监听是三年前,做一个webGIS的项目,当时对Listener的印象就是个"监视器",监视着界面的一举一动,一有动静就触发对应的响应. 一.概述 通过对界面的某一或某些操 ...
- 4.JAVA之GUI编程事件监听机制
事件监听机制的特点: 1.事件源 2.事件 3.监听器 4.事件处理 事件源:就是awt包或者swing包中的那些图形用户界面组件.(如:按钮) 事件:每一个事件源都有自己特点有的对应事件和共性事件. ...
- Node.js 教程 05 - EventEmitter(事件监听/发射器 )
目录: 前言 Node.js事件驱动介绍 Node.js事件 注册并发射自定义Node.js事件 EventEmitter介绍 EventEmitter常用的API error事件 继承EventEm ...
- .NET事件监听机制的局限与扩展
.NET中把“事件”看作一个基本的编程概念,并提供了非常优美的语法支持,对比如下C#和Java代码可以看出两种语言设计思想之间的差异. // C#someButton.Click += OnSomeB ...
- 让 select 的 option 标签支持事件监听(如复制操作)
这标题,让option支持事件监听,应该不难的呀,有什么好讲的? 其实还是有的,默认在浏览器代码是无法直接对option标签进行操作的,不仅包括JS事件监听,还是CSS样式设置 查了一些资料,姑且认为 ...
- [JS]笔记12之事件机制--事件冒泡和捕获--事件监听--阻止事件传播
-->事件冒泡和捕获-->事件监听-->阻止事件传播 一.事件冒泡和捕获 1.概念:当给子元素和父元素定义了相同的事件,比如都定义了onclick事件,点击子元素时,父元素的oncl ...
- [No00006A]Js的addEventListener()及attachEvent()区别分析【js中的事件监听】
1.添加时间监听: Chrom中: addEventListener的使用方式: target.addEventListener(type, listener, useCapture); target ...
- java 事件监听 - 鼠标
java 事件监听 - 鼠标 //事件监听 //鼠标事件监听 //鼠标事件监听有两个实现接口 //1.MouseListener 普通的鼠标操作 //2.MouseMotionListener 鼠标的 ...
随机推荐
- Apache Struts 多个开放重定向漏洞(CVE-2013-2248)
漏洞版本: Struts < 2.3.15.1 漏洞描述: BUGTRAQ ID: 61196 CVE(CAN) ID: CVE-2013-2248 Struts2 是第二代基于Model-Vi ...
- 安装zabbix2.2.3
系统版本:CentOS 6.3_x86_64 zabbix版本:zabbix-2.2.3 zabbix服务端IP:172.16.10.72 1.yum安装LAMP环境 # yum -y install ...
- 整合apache+tomcat+keepalived实现高可用tomcat集群
Apache是一个强大的Web服务器在处理静态页面.处理大量网络客户请求.支持服务的种类以及可配置方面都有优势,高速并且强壮.但是没有JSP/Servlet的解析能力.整合Apache和Tomcat可 ...
- 【动态规划】Vijos P1121 马拦过河卒
题目链接: https://vijos.org/p/1616 题目大意: 卒从(0,0)走到(n,m),只能向下或向右,不能被马一步碰到或走到马,有几种走法. 题目思路: [动态规划] 把马控制的地方 ...
- cf601A The Two Routes
A. The Two Routes time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...
- WCF—Binding
原文地址:http://www.cnblogs.com/jams742003/archive/2010/01/13/1646379.html Binding描述了哪些层面的信息 一个Binding包含 ...
- [Java] JavaMail 发送 html 格式、带附件的邮件
本案例演示发送 html 格式,可带附件的邮件发送.发送纯文本邮件的例子可参照上一篇博文JavaMail 简单案例. EmailHelper, Email 的帮助类,向帮助类提供 SMTP 服务器域名 ...
- Android ===smail语法总结
(转载自 网络)smail 语法总结 http://www.blogjava.net/midea0978/archive/2012/01/04/367847.html Smali背景: Smali,B ...
- 【.NET调用Python脚本】C#调用python requests类库报错 'module' object has no attribute '_getframe' - IronPython 2.7
最近在开发微信公众号,有一个自定义消息回复的需求 比如用户:麻烦帮我查询一下北京的天气? 系统回复:北京天气,晴,-℃... 这时候需要根据关键字[北京][天气],分词匹配需要执行的操作,然后去调用天 ...
- SQL Server不区分大小写的问题
SQL Server不区分大小写的问题 默认情况下,SQL Server不区分大小写,如果数据表TEST的TNAME列中有数据“abcd”和“Abcd”, 如果使用查询语句:select * fr ...