openSession() 与 getCurrentSession()有何不同和关联呢
使用Hibernate我们都知道建立Session的建立方式有以上两种,openSession和getCurrentSession两种方式。
引用一些别人对session的定义:
Session:一般的持久化方法(CRUD)都是通过 Session 来调用的,Session
是非线程安全的。
Session 的创建与关闭:Session 是一个轻量级对象,通常将每个Session
实例和一个数据库事务绑定,也就是每执行一个数据库事务,都应该先创建
一个新的Session 实例,在使用Session 后,还需要关闭Session。
Session 的创建
创建SessionFactory 后,就可以通过SessionFactory 创建Session 实例,通过
SessionFactory 创建Session 实例的代码如下。
Session session=sessionFactory.openSession();
创建Session 后,就可以通过创建的Session 进行持久化操作了。
Session 的关闭
在创建Session 实例后,不论是否执行事务,最后都需要关闭Session 实例,
释放Session 实例占用的资源。
关闭Session 实例的代码如下:
session.close();
下面来解释一下上面两者创建Session的方法的区别:
1.getCurrentSession 创建的session 会和绑定到当前线程,而openSession
不会。
2 getCurrentSession 创建的线程会在事务回滚或事物提交后自动关闭,而
openSession 必须手动关闭,假如你调用了getCurrentSession方法后,而后你又忘记了,手动又调用了session.close()方法。那么将会报错,系统提示你session已经关闭。
3. getCurrentSession() 使用当前的session,openSession() 重新建立一个
新的session
这里getCurrentSession 本地事务(本地事务:jdbc)时要在配置文件(hibernate.cfg.xml)里进行
如下设置
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</prop
erty>
* 如果使用的是全局事务(jta 事务)
<property name="hibernate.current_session_context_class">jta</property
>
在SessionFactory 启动的时候,Hibernate 会根据配置创建相应
的CurrentSessionContext,在getCurrentSession() 被调用的时候,实际被执
行的方法是CurrentSessionContext.currentSession() 。在currentSession() 执
行时,如果当前Session 为空,currentSession 会调
用SessionFactory 的openSession。所以getCurrentSession() 对
分析:Hibernate 可以配置为JDBCTransaction 或者是JTATransaction,这取决于你
在hibernate.properties 或者hibernate.cfg.xml 中的配置
本文详细对比了Hibernate框架中openSession和getCurrentSession两种创建Session的方式。openSession创建的Session不与线程绑定,需手动关闭;而getCurrentSession创建的Session与当前线程绑定,并在事务结束后自动关闭。
687

被折叠的 条评论
为什么被折叠?



