[Hibenate] openSession() 和 getCurrentSession的区别

1.采用getCurrentSession()创建的Session会绑定到当前的线程中去;

而采用OpenSession()则不会。

2.采用getCurrentSession()创建的Session在commit或rollback后会自动关闭;

采用OpenSession()必须手动session.close()关闭。

3.采用getCurrentSession()需要在Hibernate.cfg.xml配置文件中加入如下配置:

未绑定当前线程会出现异常:

org.hibernate.HibernateException: No Hibernate Session bound to thread

* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)

<property name="hibernate.current_session_context_class">jta</property>

 

 

另外,但是在使用getCurrentSession(),必须在事务中运行,要不出

org.hibernate.HibernateException: createQuery is not valid without active transaction

 

[转载自:http://blog.sina.com.cn/s/blog_5f53615f0100tnej.html]

原文地址:https://www.cnblogs.com/kentyouyou/p/3146280.html