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>
非常感谢@gkamal。我查看[Open View in View](http://community.jboss.org/wiki/OpenSessionInView)文件中的代码。 (您的链接指向该文档。)作者建议使用过滤器。在他的过滤代码中,他不会调用'openSession()'或'close()'。他只调用'getCurrentSession()'。我猜他把'current_session_context'设置为'thread'。现在我想我理解'getCurrentSession()'。但是,我不知道什么时候应该使用'openSession()'。 – wannik
如果您不想将会话绑定到任何上下文,您将使用OpenSession。在某些情况下,你需要一个不同的会话 - 除了绑定到上下文之外(Hibernate拦截器有一个局限性,你不能使用原始会话) - 在这种情况下,你将使用OpenSession而不是currentSession。 OpenSession创建一个新的会话,您必须明确关闭。例如,在DAO方法中,您将调用OpenSession - 使用会话并关闭它。 – gkamal
am使用getCurrentSession();因为我在监听器中初始化它,而不是过滤器从您的视图中可以看到;我正在使用mvc2 jsp servlet – shareef