org.hibernate.StaleStateException 每当嵌套事务启动时

问题描述 投票:0回答:1

我遇到了 Hiberate 的问题,我无法弄清楚。场景是:

  1. 新会话和交易已启动
  2. 版本号为 10 的实体已加载
  3. 新事务通过@Transactional(propagation = Propagation.REQUIRES_NEW)启动
  4. 当这个新事务提交并刷新时,实体版本提升到11
  5. 原始事务提交、刷新,但不知道版本已提升,因此尝试更新版本为 10 的位置,但版本现在已经是 11,因此失败并显示

原因:org.hibernate.StaleStateException:批量更新从更新[0]返回意外的行数;实际行数:0;预期:1;执行的语句: update COMMON.WORKSPACE set VERSION=?, MODEL=?其中ID=?和版本=?

我不知道问题出在哪里。我猜新交易不应该打开新会话?或者新事务中的刷新是否应该将版本更改传播到原始会话?

Hibernate 版本是 5.6。

我尝试将刷新模式从自动更改为提交,但这使事情变得更糟。

java hibernate
1个回答
0
投票
  1. 您可以手动将第二个事务的更改合并到第一个事务的会话中,如下所示,

     @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);
     }
    
  2. 对两个事务使用相同的会话:确保两个事务在同一个 Hibernate 会话中运行。这可以通过避免对第二个事务使用 REQUIRES_NEW 或通过在两个事务之间显式共享会话上下文来实现。

© www.soinside.com 2019 - 2024. All rights reserved.