Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Hibernate中编程式事务的简单使用

一,openSessioin方式开启或者关闭事务                Session session = null;
  try {
   session = HibernateUtils.getSession();
   session.beginTransaction();//开启事务
   
   //TODO:各类CRUD操作
   
   session.getTransaction().commit(); //提交事务
  } catch (Exception e) {
   e.printStackTrace();
   session.getTransaction().rollback(); //出错回滚
  } finally {
   HibernateUtils.closeSession(session); //关闭session
  }使用这种方式开启和关闭事务,但是考虑到我们的事物一般都是在Service层开启或者关闭的,而service里面在调用Dao层方法的时候,大部分情况下,都是调用多个方法,即一对多的调用,要想保证我每次开启事务的时候,用的都是一个Session,上面这种简陋的方法就不行了。二,getCurrentSession使用事务1,添加使用currentSession的配置<property name="hibernate.current_session_context_class">thread</property><!-- 将session放到threadLoacl里面 -->2,替换getSession方法对与如下图,其中要在单元测试类中添加测试用户方法:代码:每次获取session的时候,使用getCurrentSession方法,获取当前线程使用的Session。同样,在添加log的时候也使用上面方法获取session,这样就能保证我一连串的CRUD操作的时候,使用的是一个Session。小结:*openSession是必须要关闭session的,而currentSession是在事务结束之后自动关闭session*opsenSession没有和当前线程绑定,currentSession和当前线程绑定了*使用currentSession的时候需要在hibernate的配置文件中进行配置Hibernate学习入门教程  http://www.linuxidc.com/Linux/2015-08/121498.htm在Hibernate中开启日志 http://www.linuxidc.com/Linux/2015-07/120499.htmHibernate+JUnit测试实体类生成数据库表  http://www.linuxidc.com/Linux/2015-07/120161.htmHibernate整体理解 http://www.linuxidc.com/Linux/2014-07/104405.htmHibernate的映射机制  http://www.linuxidc.com/Linux/2014-12/110265.htmHibernate 的详细介绍:请点这里
Hibernate 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-02/128408.htm