java b/w Hibernate 的 Sessionfactory.getCurrentSession() 和 SessionFactory.openSession() 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10072367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference b/w Hibernate's Sessionfactory.getCurrentSession() and SessionFactory.openSession()
提问by tintin
I'm a little confused between the two. As per I know both returns hibernate session, SessionFactory.getCurrentSession()
returns a contextual session based on the property <property name="current_session_context_class">
which is set in hibernate.cfg.xml
Shouldn't we always go with this approach?
我在两者之间有点困惑。据我所知,两者都返回休眠会话,SessionFactory.getCurrentSession()
返回基于<property name="current_session_context_class">
hibernate.cfg.xml 中设置的属性的上下文会话我们不应该总是采用这种方法吗?
What additional value is added by SessionFactory.openSession()
?
增加了什么附加价值SessionFactory.openSession()
?
回答by Hardik Mishra
A session is opened whenever sf.getCurrentSession()
is called for the first time. This creates a brand new session if one does not exist or uses an existing one if one already exists.
每当sf.getCurrentSession()
第一次调用时就会打开一个会话。如果一个会话不存在,这将创建一个全新的会话,或者如果一个已经存在,则使用现有的会话。
In Tomcat this associates a session with a thread which is created using the underlying ThreadLocal
object. But since Tomcat uses thread pooling it is entirely possible that a request may receive a thread with a session already associated with it, thus introducing the possibility of not even creating a brand new session. Another thing is that The Session that you obtained with sf.getCurrentSession()
is flushed and closed automatically.
在 Tomcat 中,这将会话与使用底层ThreadLocal
对象创建的线程相关联。但是由于 Tomcat 使用线程池,因此请求可能会收到一个会话已经与其关联的线程,因此引入了甚至不创建全新会话的可能性。另一件事是您获得的 Session 会sf.getCurrentSession()
自动刷新和关闭。
The method sf.openSession()
on the other hand creates a new session but does not attempt to associate it with a thread. But remember sf.openSession()
introduces another hitch in that it expects users to handle the closing and flushing of sessions themselves, instead of letting Hibernate do it automatically for us.
sf.openSession()
另一方面,该方法会创建一个新会话,但不会尝试将其与线程相关联。但是请记住sf.openSession()
引入了另一个问题,因为它希望用户自己处理会话的关闭和刷新,而不是让 Hibernate 自动为我们完成。
sf.getCurrentSession()
is usually sufficient. sf.openSession()
provides and facilitates a greater level of management of where the session is stored and managed. It's certainly an advanced option.
sf.getCurrentSession()
通常就足够了。sf.openSession()
提供并促进对会话存储和管理位置的更高级别的管理。这当然是一个高级选项。