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

Sri*_*vas 18 java session spring 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)
Run Code Online (Sandbox Code Playgroud)

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

yun*_*ace 50

如果你使用Dropwizard Hibernate.您需要向@UnitOfWorkResource方法添加注释.有关详细信息,请参阅dropwizard手册,hibernate章节.

  • 最佳答案 (3认同)

Arp*_*wal 3

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

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

hibernate-cfg.xml使用以下行编辑您的:

hibernate.current_session_context_class=org.springframework.orm.hibernate3.SpringSessionContext
Run Code Online (Sandbox Code Playgroud)

上面的线会做什么?

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