【问题标题】:org.hibernate.HibernateException: get is not valid without active transactionorg.hibernate.HibernateException:没有活动事务获取无效
【发布时间】:2012-03-15 10:30:29
【问题描述】:

我是 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>

【问题讨论】:

  • 能否添加调用get()方法的代码?
  • @ShashankKadne CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);
  • 添加“交易 tx = session.beginTransaction();”就在这一行之前和操作结束时调用“tx.commit();”
  • @ShashankKadne 谢谢,它有效
  • :我会添加它作为答案然后...

标签: java hibernate netbeans netbeans-7


【解决方案1】:

添加

Transaction tx = session.beginTransaction(); //这条语句会发起事务

就在你的CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);之前

并在事务结束时通过调用提交更改..

tx.commit();

【讨论】:

  • 为什么 eclipse hibernate 工具不会自动生成这个?
【解决方案2】:

另一种解决方案是使用openSession() 而不是getCurrentSession()。只有在需要更新查询时才能使用事务。

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

【讨论】:

  • 我正在经历这种情况,即通过 getCurrentSession 获得的会话即使对于 get 操作也需要事务,而这在使用 openSession 时并不适用。这是为什么? (我以为会话对象是相同的?)
  • 我遇到了同样的问题。但为什么呢?
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

    在您真正开始事务之前,您需要在创建 sessionFactory 之后立即通过调用 session.beginTransaction() 来启动会话。

    【讨论】:

      猜你喜欢
      • 2012-08-13
      • 2014-09-07
      • 1970-01-01
      • 2015-03-05
      • 2014-08-13
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多