您可能知道有两种方法可以在休眠中创建或获取会话。我们在 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 之间的区别
原文链接:https://codingdict.com/