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的配置文件里进行配置



         
          




原文地址:https://www.cnblogs.com/jzssuanfa/p/6960941.html