Hibernate中openSession和getCurrentSession的区别


您可能知道有两种方法可以在休眠中创建或获取会话。我们在 SessionFactory 类中有以下两种方法来创建会话。

  • 开放会话
  • 获取当前会话

现在我们将看到 openSession 和 getCurrentSession 之间的区别。

开放会话

当您调用 SessionFactory.openSession 时,它总是会重新创建新的 Session 对象并将其提供给您。您需要显式刷新和关闭这些会话对象。由于会话对象不是线程安全的,因此您需要在多线程环境中为每个请求创建一个会话对象,在 Web 应用程序中也需要为每个请求创建一个会话。

获取当前会话

当你调用 SessionFactory. getCurrentSession,它将为您提供在休眠上下文中并由休眠内部管理的会话对象。它绑定到事务范围。

当你调用 SessionFactory. getCurrentSession ,如果不存在则创建一个新会话,否则使用当前休眠上下文中的相同会话。它会在事务结束时自动刷新并关闭会话,因此您无需在外部进行。

如果您在单线程环境中使用休眠,则可以使用 getCurrentSession,因为与每次创建新会话相比,它的性能更快。

您需要将以下属性添加到 hibernate.cfg.xml 以使用 getCurrentSession 方法。

<session-factory>
<!--  Put other elements here -->
<property name="hibernate.current_session_context_class">
          thread
</property>
</session-factory>

如果您不配置上述属性,您将收到如下错误。

Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012)
    at com.arpit.java2blog.hibernate.HibernateSessionExample.main(HibernateSessionExample.java:14)

openSession 与 getCurrentSession :

让我们在下表中总结 openSession 和 getCurrentSession 之间的区别

范围 openSession getCurrentSession
Session object 它总是创建新的 Session 对象 如果不存在,它将创建一个新会话,否则使用当前休眠上下文中的相同会话
Flush and close 您需要显式刷新和关闭会话对象 您不需要刷新和关闭会话对象,它将由 Hibernate 内部自动处理
Performance 在单线程环境中,它比 getCurrentSession 慢 在单线程环境下,比 getOpenSession 快
Configuration 您无需配置任何属性即可调用此方法 你需要配置额外的属性“hibernate.current_session_context_class ”来调用getCurrentSession方法,否则会抛出异常。


原文链接:https://codingdict.com/