Hibernate的Sessionfactory.getCurrentSession()和SessionFactory.openSession()的区别

丁丁:

我对两者有些困惑。据我所知,这两个方法都返回休眠会话,SessionFactory.getCurrentSession()并基于<property name="current_session_context_class">hibernate.cfg.xml中设置的属性返回上下文会话,我们不应该总是使用这种方法吗?

附加值是SessionFactory.openSession()多少?

Hardik Mishra:

每当sf.getCurrentSession()首次调用时,都会打开一个会话如果一个会话不存在,这将创建一个全新的会话;如果已经存在,则使用一个现有的会话。

在Tomcat中,这将会话与使用基础ThreadLocal对象创建的线程相关联但是,由于Tomcat使用线程池,因此完全有可能一个请求接收到一个线程,该线程具有已经与该会话关联的会话,从而带来了甚至不创建全新会话的可能性。另一件事是,您获得的会话将sf.getCurrentSession()自动刷新并关闭。

sf.openSession()另一方面,该方法创建一个新会话,但不尝试将其与线程关联。但是请记住sf.openSession(),它引入了另一个障碍,那就是希望用户自己处理会话的关闭和刷新,而不是让Hibernate为我们自动进行。

sf.getCurrentSession()通常就足够了。sf.openSession()提供并促进了会话存储和管理位置的更高级别的管理。当然,这是一个高级选项。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

sessionfactory.openSession()和sessionfactory.openStatelessSession()之间的区别?

休眠:sessionFactory.openSession()VS sessionFactory.getCurrentSession()

Hibernate 4中的SessionFactory.openSession(Connection)

Spring Hibernate-CrudRepository和SessionFactory之间的区别

正确配置以模拟Hibernate的sessionFactory.getCurrentSession()

NoSuchMethodError:org.hibernate.SessionFactory.getCurrentSession()

Spring + Hibernate:sessionFactory.getCurrentSession()导致NullPointerException

Hibernate OpenSession()与GetCurrentSession()

休眠,sessionFactory.openSession挂起

java.lang.NoSuchMethodError:org.hibernate.SessionFactory.openSession()Lorg / hibernate / classic / Session

sessionFactory与HttpSession之间的区别?在Spring + Hibernate应用程序中?

在Hibernate中使用SessionFactory.getCurrentSession()时获取Connection对象

hibernate SessionFactory.openSession()是否等待池中的数据库连接可用

Hibernate SessionFactory与Spring LocalSessionFactoryBean

Hibernate SessionFactory与JPA EntityManagerFactory

Hibernate + Spring SessionFactory配置

无法使用Hibernate和Servlet创建SessionFactory

何时使用OpenSession()和GetCurrentSession()

未为类型SessionFactory定义方法getCurrentSession()

Spring 3.1,Hibernate 4,SessionFactory

使用hibernate sessionFactory还是JPAEntityManager?

Hibernate SessionFactory,动态设置TransactionIsolationLevel

Hibernate初始SessionFactory创建失败

获取文件路径-Hibernate SessionFactory

Hibernate sessionFactory的程序化配置需要“ sessionFactory”或“ hibernateTemplate”

Spring和Hibernate5。SessionFactory始终为null

定义在Hibernate SessionFactory之前启动的Micronaut bean

无法建立Hibernate SessionFactory;嵌套异常

Spring / Hibernate集成中的NPE SessionFactory