`
john.zhang
  • 浏览: 15463 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

SessionFactory对象中getCurrentSession() 和 OpenSession()的区别

 
阅读更多

SessionFactory.getCurrentSession与openSession的区别


  a.  如果使用的是getCurrentSession来创建session的话,在commit后,session就自动被关闭了,也就是不用再     session.close()了。但是如果使用的是openSession方法创建的session的话,
  那么必须显示的关闭session,也就是调用session.close()方法。这样commit后,session并没有关闭
 b.  getCurrentSession的使用可以参见hibernate\hibernate-3.2\doc\tutorial\src项目
 c.  使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:
  * 如果采用jdbc独立引用程序配置如下:
  <property name="hibernate.current_session_context_class">thread</property>
  * 如果采用了JTA事务配置如下  
  <property name="hibernate.current_session_context_class">jta</property>

 

 

1. Dao里面写了一个方法

  SessionFactory sf = hibernateTemplate.getSessionFactory();
  Session s = sf.getCurrentSession();
  //用spring管理了事务,不用写beginTransaction()
  //s.beginTransaction();
  s.createQuery("update User u set u.name=:name,u.address=:address  where id = :id")
  .setString("name", "zhangqiang")
  .setString("address", "北京市,海淀区")
  .setString("id", "2").executeUpdate();
  //s.getTransaction().commit();

 

2.  因为在spring中已经配置了事务,这里在写beginTransaction(),就会报
Transaction not successfully started异常

将其代码注释,如上面代码

附上spring中的事务配置

<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
	<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 1. 配置基于 注解的事务驱动
<tx:annotation-driven transaction-manager="transactionManager"/>
 -->
	 
<!-- 2.1 声明事物通知 方法使用哪些事物属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<tx:attributes>
		<!-- 配置事务属性 为那些方法配置事物属性,eg:事物传播性(REQUIRES(常用), REQUIERS_NEW),事物的隔离级别,设置事物的回滚属性(运行异常, 检查异常(IOException)),事物超时回滚时间, 事物是否只读 -->
		<tx:method name="insert" propagation="REQUIRED"/>
		<tx:method name="update" propagation="REQUIRED"/>
		<tx:method name="get*" propagation="REQUIRED"/>
		<tx:method name="delete" propagation="REQUIRED"/>
		<tx:method name="findAll*" read-only="true"/>
	</tx:attributes>
</tx:advice> 
	
<!-- 2.2 配置事务的应用 配置对哪些类的哪些方法使用事物管理 -->
<aop:config proxy-target-class="true">
	<aop:pointcut expression="execution(* com.tieba.hibernate.dao.*.*(..))" id="txPontCut" />
	<aop:advisor advice-ref="txAdvice" pointcut-ref="txPontCut" />
</aop:config>

  

 

3. 或者将SessionFactory.getCurrentSession() 改为 SessionFactory.OpenSession();

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics