Hibernate 在操作数据库的时候要执行很多操作,这些动作对用户是透明的。这些操作主要是有拦截器和时间组成

hibernate拦截器可以拦截大多数动作,比如事务开始之后(afterTransactionBegin)、事务完成之前(beginTransactionCompletion)、事务完成之后(afterTransactionCompletion)、持久化对象之前(onSave),一个拦截器必须实现org.hibernate.Interceptor借口,hibernate提供了一个实现该借口的类EmptyInterceptor类

下面编写一个hibernate实例来说明hibernate拦截器的作用

首先编写一个保存持久化对象的信息类EntityInfo

public class EntityInfo {public Object entityBean;public Serializable id;public String[] properties;public Object getEntityBean() {return entityBean;}public void setEntityBean(Object entityBean) {entityBean = entityBean;}public Serializable getId() {return id;}public void setId(Serializable id) {this.id = id;}public String[] getProperties() {return properties;}public void setProperties(String[] properties) {this.properties = properties;}public String toString(){String info = "";if(entityBean !=null){info = entityBean.getClass().toString()+"\r\nid:"+id+"\r\n";if(properties != null){//处理properties中的所有元素for(String property:properties){//得到getter方法名try {String getter = "get" + property.substring(0, 1).toUpperCase()+property.substring(1);//使用反射技术和gettter方法名获得Method对象Method method = entityBean.getClass().getMethod(getter);//调用gettter方法,并追加生成要返回的信息info = info + property + ":" +method.invoke(entityBean).toString() +"\r\n";} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}return info;}
}

实现拦截器类,代码如下

public class EntityBeanInterceptor extends EmptyInterceptor {private ThreadLocal entityBeans = new ThreadLocal();@Overridepublic void afterTransactionBegin(Transaction tx){entityBeans.set(new HashSet<EntityInfo>());}@Overridepublic void afterTransactionCompletion(Transaction tx){if(tx.wasCommitted()){Iterator i =  ((Collection)entityBeans.get()).iterator();while (i.hasNext()) {//在提交事务之后输出试题bean的内容EntityInfo info = (EntityInfo) i.next();//调用方法数据EntityBean对象processEntityBean(info);}}}private void processEntityBean(EntityInfo info){System.out.println(info);}@Overridepublic boolean onSave(Object entity,Serializable id, Object[] state,String[] propertyNames,Type[] types){EntityInfo info = new EntityInfo();info.entityBean = entity;info.properties = propertyNames;info.id =id;//在持久化对象后,将对象信息保存到当前线程的HashSet<EntityInfo>对象中((HashSet<EntityInfo>) entityBeans.get()).add(info);return false;}}

注册拦截器类,本例中在构造Session时创建拦截器类

public class HibernateSessionFactory {/*其他代码省略*/private static ThreadLocal threadLocal = new ThreadLocal();private  static Configuration configuration = new Configuration();private static org.hibernate.SessionFactory sessionFactory;public static Session getSession(Interceptor... interceptor){Session session = (Session) threadLocal.get();if(session == null || !session.isOpen()){//如果session为空重新建立一个Session工厂if(sessionFactory == null){rebuildSessionFactory();}//如果interceptor参数值中包含拦截器对象,则安装该拦截器session = (sessionFactory != null)?((interceptor.length == 0)?sessionFactory.openSession():sessionFactory.openSession(interceptor[0])):null;//如果ThreadLocal对象中没有属于当前线程的session对象,则添加一个Session对象threadLocal.set(session);}}}

测试拦截器类

public class TestInterceptor {private void mian() {
// TODO Auto-generated method stub
Session session = HibernateSessionFactory.getSession(new EntityBeanInterceptor());
Transaction tx = session.beginTransaction();
//Customer是一个实体bean
Customer customer = new Customer();
customer.setName("hqw");
session.saveOrUpdate(customer);
tx.commit();
session.close();
}
}

这样在构造session时就注册了拦截器,应为本文在EntityInterceptor类中注册了在事务开始后、事务完成后、持久化后三个方法,所以在相应地方就会调用拦截器中的方法

转载于:https://www.cnblogs.com/haquanwen/p/3812609.html

Hibernate 拦截器实例相关推荐

  1. Hibernate 拦截器 Hibernate 监听器

    Hibernate拦截器(Interceptor)与事件监听器(Listener) 拦截器(Intercept):与Struts2的拦截器机制基本一样,都是一个操作穿过一层层拦截器,每穿过一个拦截器就 ...

  2. 根据hibernate拦截器实现可配置日志的记录

    对于日志和事件的记录在每个项目中都会用到,如果在每个manager层中触发时间记录的话,会比较难以扩展和维护,所以可配置的日志和事件记录在项目中会用到! 首先在spring的配置文件中加入hibern ...

  3. Struts2自定义拦截器实例—登陆权限验证

    版本:struts2.1.6 此实例实现功能:用户需要指定用户名登陆,登陆成功进入相应页面执行操作,否则返回到登陆页面进行登陆,当直接访问操作页面(登陆后才能访问的页面)时则不允许,须返回登陆页面. ...

  4. Hibernate 拦截器的使用--动态表名

    2019独角兽企业重金招聘Python工程师标准>>> 摘要: jpa有多种实现的方式,但是最常见的还是采用Hibernate的方式实现,所以为了实现上述的业务,就必须得用到Hibe ...

  5. Struts2自己定义拦截器实例—登陆权限验证

    版本号:struts2.1.6 此实例实现功能:用户须要指定username登陆,登陆成功进入对应页面运行操作,否则返回到登陆页面进行登陆,当直接訪问操作页面(登陆后才干訪问的页面)时则不同意,须返回 ...

  6. Struts2拦截器实例-权限拦截器

    查看本例之前首先要大概了解struts2的理论知识(点击查看) 本例实现了一个权限拦截器! 需求:要求用户登录,且必须为指定用户名才可以查看系统中的某个视图资源,如果不满足这两个条件,系统直接转入登录 ...

  7. php扩展拦截请求,PHP的拦截器实例分析

    class intercept_demo{ private $xingming = ""; private $age = 10; // 若访问一个未定义的属性,则将调用get{$p ...

  8. SpringMVC03之拦截器和JSR303

    目录 1.什么是拦截器 2.拦截器与过滤器 2.1 什么是过滤器(Filter) 2.2 拦截器与过滤器的区别 3.应用场景 4.拦截器快速入门 4.1 入门案例 4.2 拦截器方法说明---详见&l ...

  9. springmvc 03(JSR303和拦截器)

    目录 一,JSR303 1.服务端验证 2.步骤 二,拦截器 1.简介 2.拦截器与过滤器 2.1 什么是过滤器 2.2 拦截器和过滤器的区别 3.拦截器案例 3.1 使用原理 一,JSR303 1. ...

最新文章

  1. python包 wget_Python数据科学“冷门”库
  2. Android完全退出程序、线程
  3. MYSQL-用户操作
  4. java资源分配算法,java - 资源分配与动态规划算法 - 堆栈内存溢出
  5. Nginx报错:nginx: [emerg] CreateFile() nginx.conf“ failed (3: The system cannot find the path specified
  6. 点击按钮弹出iframe_WEB安全(四) :CSRF与点击劫持
  7. 解决org.springframework.web.multipart.MaxUploadSizeExceededException报错问题
  8. c语言链表末尾怎么插入数据,在链表中插入数据!求助!!!
  9. Facebook广告系统及多账号操作经验分享
  10. Fast Intro To Java Programming (2)
  11. OpenResty HelloWorld
  12. unity相机的两种不模式的区别
  13. 大数据综合实验的踩坑总结(林子雨)
  14. 普中28335开发攻略_凌乱的DSP笔记(1)-F28335基础知识
  15. 此为四川大学110周年校庆大型文艺晚会朗诵文稿
  16. 最小二乘法拟合直线——MATLAB和Qt-C++实现
  17. intern()详解
  18. prometheus命令_Prometheus配置
  19. BLAS 1级例程(向量-向量操作)
  20. python pandas excel 排序_Python pandas对excel的操作实现示例

热门文章

  1. POJ-2777-CountColor(线段树,位运算)
  2. TPC-H生成Spark测试用的伪数据集(转载)
  3. RSA key format is not supported
  4. no such file or directory, open '/usr/share/haroopad/Libraries/.locales/zh-tw/menu.json'
  5. 08_MinNumberInRotateArrary
  6. Ubuntu16.04下面壁纸切换软件variety设置
  7. C++自定义函数实现灰度图转化
  8. java性能调优工具--笔记
  9. python json.loads json.dumps(ensure_ascii = False) 汉字乱码问题解决
  10. 巅峰对话:畅想大数据时代的车联网与智能汽车