休眠 openSession() 与 getCurrentSession() [英] Hibernate openSession() vs getCurrentSession()

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

问题描述

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

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

  1. hibernate.current_session_context_class 的值应该是多少?

那么,应该使用以下哪个语句?为什么?

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

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

  • 最后,每个 Web 应用程序一个会话"或每个请求一个会话"哪个更好?

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

    推荐答案

    如本论坛所述 post,1 和 2 是相关的.如果您将 hibernate.current_session_context_class 设置为线程,然后实现类似于打开会话的 servlet 过滤器的功能 - 那么您可以使用 SessionFactory.getCurrentSession().

    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() 总是会打开一个新会话,一旦您完成操作,您必须关闭该会话.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.

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

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

    您永远不应该为每个 Web 应用程序使用一个会话 - 会话不是线程安全对象 - 不能被多个线程共享.您应该始终使用每个请求一个会话"或每个事务一个会话"

    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"

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

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