我正在使用 java 命令行应用程序测试 hibernate 4.1.9。我已将当前 session 上下文配置为线程:
<property name="hibernate.current_session_context_class">thread</property>
但是当我调用 sessionFactory.getCurrentSession()
时它抛出一个异常:
Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at com.sun.proxy.$Proxy9.get(Unknown Source)
....
我可以使用openSession
,这并不重要(毕竟这是一个测试)。我很好奇为什么我无法让方法 getCurrentSession
像宣传的那样工作。
谢谢。
最佳答案
第一次调用 sessionFactory.getCurrentSession() 确实会返回一个新 session 。问题出在我的配置上。
我是这样的:
<property name="hibernate.current_session_context_class">thread</property>
改成这样后,成功了:
<property name="current_session_context_class">thread</property>
关于java - hibernate - getCurrentSession - get 在没有 Activity 事务的情况下无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15148321/