Hibernate openSession()vs getCurrentSession() [英] Hibernate openSession() vs getCurrentSession()

查看:61
本文介绍了Hibernate openSession()vs getCurrentSession()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. <$ c $的值应该是 hibernate.current_session_context_class


  2. 然后,应该使用以下哪个语句?为什么?

      Session s = HibernateUtil.getSessionFactory()。openSession(); 
    Session s = HibernateUtil.getSessionFactory()。getCurrentSession()


  3. 哪一个更好?每个Web应用程序一个会话或每个请求一个会话?

  4. 正如本论坛所解释信息,1和2有关。如果将 hibernate.current_session_context_class 设置为线程,然后实现类似打开会话的servlet过滤器 - 那么您可以通过使用 SessionFactory.getCurrentSession()



    SessionFactory.openSession()新的会议,你必须关闭,一旦你完成了操作。 SessionFactory.getCurrentSession()返回一个绑定到上下文的会话 - 您不需要关闭它。



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



    您不应该使用 one会话每个Web应用程序 - 会话不是线程安全对象 - 不能由多个线程共享。您应始终使用每个请求一个会话或每个交易一个会话


    I have some questions about using Hibernate in JSP web application.

    1. What should be the value for hibernate.current_session_context_class?

    2. Then, which of the following statements should be used? And why?

       Session s = HibernateUtil.getSessionFactory().openSession();
       Session s = HibernateUtil.getSessionFactory().getCurrentSession()
      

    3. Lastly, which one is better "one session per web app" or "one session per request"?

    解决方案

    As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession().

    SessionFactory.openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession() returns a session bound to a context - you don't need to close this.

    If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.

    You should never use one session per web app - session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"

    这篇关于Hibernate openSession()vs getCurrentSession()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆