【发布时间】:2017-02-06 08:20:19
【问题描述】:
此代码工作正常并已部署。但是经过一段时间或几天后,刷新的数据没有反映在数据库中
protected boolean update(Object entity) {
EntityManager entityManager = null;
try {
entityManager = this.createEntityManager();
EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
entityManager.merge(entity);
entityManager.flush();
tx.commit();
return true;
} catch (Exception e) {
logger.error("Exception thrown in update(): " + e.getMessage());
tx.rollback();
return false;
}
} catch (Exception e1) {
logger.error("Exception thrown in create(): " + e1.getMessage(), e1);
return false;
} finally {
if (entityManager != null && entityManager.isOpen()) {
this.closeEntityManager(entityManager);
}
}
}
这是我的父 dao 更新方法。
提前发送。
【问题讨论】:
-
flush 调用毫无意义,因为提交会刷新。在日志中查找您的 JPA 提供程序,了解提交(或刷新)时发生的情况。此外,您应该在 try 中添加 finally,以便您可以在 finally 中回滚(而不是在 catch 中)
-
更新事务没有错误但在DB中没有反映
-
这不是我问的。你 finally 应该在内部尝试,所以你总是回滚并抛出错误。您的 JPA 提供者的 LOG 会告诉您发生了什么(调用 SQL 等)。又名调试
-
@NeilStockton 我在 finally 块中实现了 tx.rollback。那总是无法回滚。该问题仅在相关实体更新上出现,例如,如果我们更新一个效果很好的用户实体,但关系列表部门新添加的部门未反映在数据库中。我陷入了这个问题。