随笔-4  评论-1  文章-0  trackbacks-0
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 2008-07-16 15:48 阿里 阅读(1524) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: