所以我有这个代码
public static void insert(User user) {
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction trans = em.getTransaction();
trans.begin();
try {
em.persist(user);
trans.commit();
} catch (Exception e) {
System.out.println(e);
trans.rollback();
} finally {
em.close();
}
}
但是当我运行时出现此错误
最佳答案
您需要首先检查交易是否处于 Activity 状态,感谢 EntityTransaction#isActive()
在调用rollback()
之前。
非托管环境的惯用语是:
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
try {
tx = em.getTransaction();
tx.begin();
// do some work
...
tx.commit();
}
catch (RuntimeException e) {
if ( tx != null && tx.isActive() ) tx.rollback();
throw e; // or display error message
}
finally {
em.close();
}
更多详情请查看§5.2.1来自 hibernate 的文档。
所以在你的情况下,代码应该是:
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction trans = null;
try {
trans = em.getTransaction();
trans.begin();
em.persist(user);
trans.commit();
} catch (Exception e) {
System.out.println(e);
if (trans != null && trans.isActive())
trans.rollback();
} finally {
em.close();
}
关于java - 目前没有活跃的交易,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935512/