sessionFactory.openSession()和sessionFactory.getCurrentSession()区别

getCurrentSession ()   使用当前的 session

openSession()         重新建立一个新的 session

 

-------------------------

SessionFactory.getCurrentSession() Hibernate 应用获取 Session 的常用方法。在调用该方法时, Hibernate 会从 interface CurrentSessionContext 获取当前的 Session ,这是 Hibernate 在不同组件中传递 Session 的方法。

 

CurrentSessionContext 有三个实现,分别是 ThreadLocalSessionContextJTASessionContext ManagedSessionContext

 

ThreadLocalSessionContext Session 与当前线程绑定,是使用较多的一种方案;

JTASessionContext Session JTA 事务绑定,在 JTA 环境中使用;

 

ManagedSessionContext 使应用可以通过 bind() unbind() 方法控制 Session 的绑定,主要在有 Conversation 的应用中使用(如果使用 ManagedSessionContext ,开发人员要做的事情还是很多的)。

 

CurrentSessionContext 实现的选择可以通过 hibernate.current_session_context_class 来配置。

 

另一种更常见的创建 Session 的方法是 openSession()

 

 

openSession() getCurrentSession() 有何不同和关联呢?

 

SessionFactory 启动的时候, Hibernate 会根据配置创建相应的 CurrentSessionContext ,在 getCurrentSession() 被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession() 。在 currentSession() 执行时,如果当前 Session 为空, currentSession 会调用 SessionFactory openSession 。所以 getCurrentSession() 对于 Java EE 来说是更好的获取 Session 的方法。

 

再说 ManagedSessionContext ,它提供了更灵活的绑定 Session 的方式,但是使用起来去不简单。

Hibernate CaveatEmptor 实例中有关于使用 ManagedSessionContext 的例子,但更好的选择是使用 Seam Framework

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值