我正在尝试使用最新的时间戳更新记录。不久前我得到了一个异常(exception)。现在,我没有收到异常,但记录不会在数据库中更新。
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Duplicate entry '1584034242' for key 'PRIMARY'
org.hibernate.exception.ConstraintViolationException: Duplicate entry '1584034242' for key 'PRIMARY'
在线 session.flush();
在 finally block 中。
正在更新的记录具有相同的主键(数据库中现有记录的主键),但两列的值已更改,因此它不是重复项。我原以为 saveOrUpdate
会把我救到这里,它在一段时间前就起作用了。
public void flush(Object dataStore) throws DidNotSaveRequestSomeRandomError {
Transaction txD;
Session session;
session = currentSession();
if (session.getTransaction() != null && session.getTransaction().isActive()) {
txD = session.getTransaction();
} else {
txD = session.beginTransaction();
}
try {
session.saveOrUpdate(dataStore);
} catch (MappingException e) {
e.printStackTrace();
}
try {
txD.commit();
while (!txD.wasCommitted())
;
} catch (ConstraintViolationException e) {
log.error("Unable to store data from " + dataStore.getClass().toString());
txD.rollback();
throw new DidNotSaveRequestSomeRandomError(dataStore, feedbackManager);
} catch (TransactionException e) {
log.debug("txD state isActive" + txD.isActive() + " txD is participating"
+ txD.isParticipating());
log.debug(e);
txD.rollback();
} finally {
session.flush();
txD = null;
session.close();
}
}
编辑: 进行了更多的谷歌搜索,发现我需要在我的 xml 定义中使用动态更新才能使其正常工作。
<class name="My.Java.Class"
table="MyTable" dynamic-update="true">
仍然无效,我得到了重复的条目。我没有使用更新子句,但假设 saveORUpdate 应该有效。应该有办法让它发挥作用。
或
我应该捕获 constraintViolationException 并执行强制“更新”子句吗?
最佳答案
冲洗() 方法只是与数据库同步,然后您需要提交或清除 session 才能看到更改。
如果您只是提交。它会自动刷新,您也可以从另一个 session 中看到您的更改。
关于java - 使用 saveOrUpdate hibernate : Random Exceptions and record not updated during session flush,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15566888/