Java org.hibernate.HibernateException:get在没有活动事务的情况下无效
我刚开始冬眠Java org.hibernate.HibernateException:get在没有活动事务的情况下无效,java,hibernate,netbeans,netbeans-7,Java,Hibernate,Netbeans,Netbeans 7,我刚开始冬眠 自动创建hibernate.cfg.xml(Netbeans向导) 自动创建的HibernateUtil.java 自动创建带有注释的POJO类 试图从数据库获取对象,但获取错误: Exception in thread "pool-1-thread-1" org.hibernate.HibernateException: get is not valid without active transaction at org.hibernate.context.Threa
- 自动创建hibernate.cfg.xml(Netbeans向导)
- 自动创建的HibernateUtil.java
- 自动创建带有注释的POJO类
Exception in thread "pool-1-thread-1" org.hibernate.HibernateException: get is not valid without active transaction
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:297)
获取对象:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);
hibernate.cfg.xml
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sochi_feedback</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
org.hibernate.dialogue.mysqldialogue
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/sochi_feedback
根
根
真的
org.hibernate.hql.classic.ClassicQueryTranslatorFactory
线
添加
Transaction tx=session.beginTransaction()代码>//此语句将启动事务
就在CallInfo ci=(CallInfo)会话.get(CallInfo.class,ucid)之前代码>
在事务结束时,通过调用..提交更改
tx.commit();
另一种解决方案是使用openSession()
而不是getCurrentSession()
。然后,只有在需要更新查询时才能使用事务
Session session = HibernateUtil.getSessionFactory().openSession();
CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);
即使在beginTransaction()
和commit()
之后,如果您仍然获得
Caused by: org.hibernate.HibernateException: setDefaultReadOnly is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
转到“开始”并搜索服务并重新启动数据库服务在实际启动事务之前,您需要在创建sessionFactory后立即通过调用session.beginTransaction()
来启动会话。能否添加调用get()方法的代码???@ShashankakadneCallInfo ci=(CallInfo)session.get(CallInfo.class,ucid);
在此行之前和操作结束时添加“Transaction tx=session.beginTransaction();”调用“tx.commit();”@ShashankKadne谢谢,它可以工作:我将添加它作为一个答案…为什么eclipse hibernate工具不能自动生成这个?我正经历着这一点,即通过getCurrentSession获得的会话即使对于get操作也需要一个事务,而这在使用openSession时不适用。为什么?(我原以为会话对象是相同的?)我也有同样的问题。但为什么呢?