Spring:为什么Hibernate 4中的SessionFactoryUtils类不提供getSession方法?
Spring 3.1.0 中 Hibernate 4 的 SessionFactoryUtils.getSession 方法发生了什么?应该用什么来代替? sessionFactory.getCurrentSession() 不断给我这个异常:
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:883)
有任何提示吗?
What happened to the SessionFactoryUtils.getSession method from Hibernate 4 in Spring 3.1.0 ? What should be used instead ? sessionFactory.getCurrentSession() keeps giving me this exception:
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:883)
Any hint ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
sessionFactory.getCurrentSession()
我相信“当前会话”的概念是在 Hibernate 3 中出现的,
SessionFactoryUtil
是在此之前编写的。Use
sessionFactory.getCurrentSession()
I believe the concept of a "current session" came in Hibernate 3,
SessionFactoryUtil
was written before this existed.不知道他们为什么要删除它,可能他们使用 org.hibernate.context.CurrentSessionContext 实现了更好的设计。从 这篇文章:
从 SessionFactory.getCurrentSession() 的文档:
Not sure why did they remove it, probably they implemented a better design using
org.hibernate.context.CurrentSessionContext
. As from this post:As from documentation of SessionFactory.getCurrentSession():
您必须
添加一个属性示例:thread
向会话工厂 bean 映射 。 (查看 hibernate 文档以获取更多详细信息)
You have to add a property example:
<prop key="hibernate.current_session_context_class">thread</prop>
to your session factory bean mapping. (check the hibernate documentation for more details)
当您没有使用 Spring 正确配置事务划分时,会发生“
org.hibernate.HibernateException: No Session found for current thread
”异常。通常,Spring 在事务开始时为您打开一个会话,将其绑定到 ThreadLocal 并在事务期间重复使用它。当您的事务提交时,会话将关闭(在刷新之后)。因此,您不需要自己对
SessionFactory
类进行任何调用。通常,人们将
@Transactional
放在类(通常是服务)上,并 配置 Spring 在该类的方法调用上启动和结束事务。The '
org.hibernate.HibernateException: No Session found for current thread
' exception happens when you haven't configured your transaction demarcation properly with Spring.Typically, Spring opens a session for you when your transaction starts, binds it to a ThreadLocal and re-uses it for the duration of your transaction. When your transaction commits, the session is closed (after it was flushed). So, you don't need to make any calls to the
SessionFactory
class yourself.Usually, people put
@Transactional
on a class (typically a Service) and configure Spring to start and end transactions on method invocations on that class.