当前没有会话绑定到执行上下文

时间:2015-05-13 10:25:53

标签: java hibernate dropwizard

当我使用session.getCurrentSession()时,我得到了以下异常。

我已经提到了

hibernate.current_session_context_class: managed

org.hibernate.HibernateException: No session currently bound to execution context
    at org.hibernate.context.internal.ManagedSessionContext.currentSession(ManagedSessionContext.java:75)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
    at io.dropwizard.hibernate.AbstractDAO.currentSession(AbstractDAO.java:36)
    at io.dropwizard.hibernate.AbstractDAO.persist(AbstractDAO.java:149)

我用它与dropwizard。任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:49)

如果您使用的是Dropwizard Hibernate。您需要在Resource方法中添加@UnitOfWork注释。 dropwizard manual, hibernate chapter内的更多信息。

答案 1 :(得分:2)

你可以尝试:session.openSession() - 它告诉hibernate总是打开一个新的会话,你必须在完成操作后关闭。使用session.getCurrentSession(),hibernate返回绑定到您不需要关闭的上下文的会话,只需要将hibernate.current_session_context_class设置为thread。

如果您的应用程序是基于Spring的,您还可以使用SpringSessionContext配置会话。

使用以下行修改 hibernate-cfg.xml

hibernate.current_session_context_class=org.springframework.orm.hibernate3.SpringSessionContext

以上行会做什么?

将会话上下文类设为“org.springframework.orm.hibernate3.SpringSessionContext “,Hibernate将假设它在Spring事务上下文中执行(即通过Spring事务方面),Spring现在将为您管理您的事务。但是如果您在这样的上下文之外调用getCurrentSession() ,Hibernate将抛出异常,抱怨没有Session绑定到该线程。