问题

我有一些关于在JSP Web应用程序中使用Hibernate的问题。

  • hibernate.current_session_context_class的值应该是多少?
  • 那么,应该使用以下哪个陈述?为什么? Session s = HibernateUtil.getSessionFactory()。openSession();
     Session s = HibernateUtil.getSessionFactory()。getCurrentSession()
  • 最后,哪个更好"每个网络应用一个会话"或"每个请求一个会话"?

#1 热门回答(126 赞)

如本论坛post中所述,1和2是相关的。如果你将hibernate.current_session_context_class设置为线程然后实现类似于打开会话的servlet过滤器 - 那么你可以使用41100397在其他任何地方访问该会话。

SessionFactory.openSession()总是打开一个新的会话,一旦完成操作,就必须关闭它.1444349447返回绑定到上下文的会话 - 你不需要关闭它。

如果你使用Spring或EJB来管理事务,则可以将它们配置为打开/关闭会话以及事务。

你永远不应该使用one session per web app-会话不是一个线程安全的对象 - 不能由多个线程共享。你应该始终使用"每个请求一个会话"或"每个事务一个会话"


#2 热门回答(16 赞)

如果我们谈论SessionFactory.openSession()

  • 它始终创建新的Session对象。
  • 你需要显式刷新和关闭会话对象。
  • 在单线程环境中,它比getCurrentSession慢。
  • 你无需配置任何属性即可调用此方法。

如果我们谈论SessionFactory.getCurrentSession()

  • 如果不存在,它会创建一个新的Session,否则使用当前hibernate上下文中的相同会话。
  • 你不需要刷新和关闭会话对象,Hibernate会在内部自动处理它。
  • 在单线程环境中,它比openSession更快。
  • 你需要配置其他属性。 "hibernate.current_session_context_class"调用getCurrentSession方法,否则会抛出异常。

#3 热门回答(1 赞)

openSession :- When you call SessionFactory.openSession, it always create new Session object afresh and give it to you.

你需要显式刷新和关闭这些会话对象。由于会话对象不是线程安全的,因此你需要在多线程环境中为每个请求创建一个会话对象,并在Web应用程序中为每个请求创建一个会话。

getCurrentSession :- When you call SessionFactory. getCurrentSession, it will provide you session object which is in hibernate context and managed by hibernate internally. It is bound to transaction scope.
When you call SessionFactory. getCurrentSession , it creates a new Session if not exists , else use same session which is in current hibernate context. It automatically flush and close session when transaction ends, so you do not need to do externally.
If you are using hibernate in single threaded environment , you can use getCurrentSession, as it is faster in performance as compare to creating  new session each time.
You need to add following property to hibernate.cfg.xml to use getCurrentSession method.



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

原文链接