getHibernateTemplate().getSessionFactory().getCurrentSession()

区别

getHibernateTemplate().getSessionFactory().openSession()

getHibernateTemplate().getSessionFactory().getCurrentSession()

 

 

getCurrentSession ()   使用当前的 session

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

 

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

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

 

CurrentSessionContext 有三个实现,分别是 ThreadLocalSessionContext 、 JTASessionContext 和 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 。

 

posted on 2009-03-29 23:03 luofeng225 阅读(2746) 评论(0)  编辑  收藏 所属分类: Spring

<2009年3月>
日一二三四五六
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

导航

统计

公告

我曾经听到这么一个故事: 一个年轻的程序员问一个老程序员(一个比较牛逼的公司的CTO) 年轻程序员: 你为什么这么牛X., 就好像没有你不会的。老程序员: 积累的。年轻程序员: 怎么才能积累到您的程度呢。我每天都在积累。但是似乎都没有感觉到进步。老程序员: 我从20岁开始做到了一件事情,直到今天,而且尽可能地保证不间断。年轻程序员: 到底是什么? 老程序员: 我每天保证自己有2个小时在学习新的东西。

常用链接

留言簿(3)

随笔分类

随笔档案

文章分类

相册

收藏夹

Java Website

java技术博客

搜索

最新评论

阅读排行榜

评论排行榜