hibernate-- org.hibernate.TransactionException:事务未成功启动

RK3*_*RK3 2 hibernate

我是hibernate的初学者.当我试图将对象保存到不存在该表的DB中时.我得到一个异常org.hibernate.TransactionException:org.hibernate.engine.HibernateTest.main上的org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:170)中的事务未成功启动(HibernateTest.java: 20)

这是我的类文件,我试图将对象保存到DB中

package org.rk.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.rk.dto.UserDetails;

public class HibernateTest {

    public static void main(String[] args) {
        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("GNS");
        try {       
            SessionFactory sf = new Configuration().configure().buildSessionFactory();
            Session session = sf.openSession();
            session.save(user);
            session.getTransaction().commit();
        }
        catch(HibernateException e) {
            e.printStackTrace();
            System.out.println("in exception");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用oracle 11g发布2和hibernate 4.2.4 ..请帮忙

Has*_*bal 17

我认为你不是在任何地方开始你的交易.您已经打开了一个会话,但在开始交易之前,您正在提交它.打开会话后尝试启动它.

像这样:

try {
    // create session
    tx = session.beginTransaction();
    // do something
    tx.commit();
} catch (Exception exp) {
    tx.rollback();
    // close session
}
Run Code Online (Sandbox Code Playgroud)


ome*_*ici 8

为了避免org.hibernate.TransactionException,您可以使用以下代码.在提交之前,您可以控制它是否已提交.差异在第5行!tx.wasCommited()

try {
  // create session
  tx = session.beginTransaction();
  // do something
  if (!tx.wasCommitted()){
    tx.commit();
  }
} catch (Exception exp) {
  tx.rollback();
  // close session
}
Run Code Online (Sandbox Code Playgroud)

  • 我试图提交两次,这段代码告诉我我的错误在哪里.谢谢. (2认同)