我遇到了 Hiberate 的问题,我无法弄清楚。场景是:
原因:org.hibernate.StaleStateException:批量更新从更新[0]返回意外的行数;实际行数:0;预期:1;执行的语句: update COMMON.WORKSPACE set VERSION=?, MODEL=?其中ID=?和版本=?
我不知道问题出在哪里。我猜新交易不应该打开新会话?或者新事务中的刷新是否应该将版本更改传播到原始会话?
Hibernate 版本是 5.6。
我尝试将刷新模式从自动更改为提交,但这使事情变得更糟。
您可以手动将第二个事务的更改合并到第一个事务的会话中,如下所示,
@Transactional
public void updateEntityInSameTransaction() {
// Load entity in the current session
Entity entity = entityManager.find(Entity.class, entityId);
// Perform some operations on the entity
// Start a new transaction
updateEntityInNewTransaction(entity);
// Merge changes made in the second transaction into the first transaction's session
entityManager.unwrap(Session.class).merge(entity);
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void updateEntityInNewTransaction(Entity entity) {
// Update entity in the new transaction
entityManager.merge(entity);
}
对两个事务使用相同的会话:确保两个事务在同一个 Hibernate 会话中运行。这可以通过避免对第二个事务使用 REQUIRES_NEW 或通过在两个事务之间显式共享会话上下文来实现。