org.hibernate.HibernateException:如果没有活动事务,则get无效

时间:2012-03-15 10:30:30

标签: java hibernate netbeans netbeans-7

我是Hibernate的新手。

  • 自动创建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>

4 个答案:

答案 0 :(得分:14)

添加

Transaction tx = session.beginTransaction(); //此声明将启动交易

CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);

之前

并在您的交易结束时通过调用..

提交更改
tx.commit();

答案 1 :(得分:5)

另一种解决方案是使用openSession()代替getCurrentSession()。然后,只有在更新查询时才能使用事务。

Session session = HibernateUtil.getSessionFactory().openSession();
CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);

答案 2 :(得分:0)

即使在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) 

转到“开始”并搜索服务并重新启动数据库服务

答案 3 :(得分:0)

在实际开始交易之前,您需要在创建sessionFactory之后立即调用session.beginTransaction()来启动会话。