首页 > 解决方案 > Spring JPA 合并 - ObjectOptimisticLockingFailureException

问题描述

Spring Data JPA 合并失败 - ObjectOptimisticLockingFailureException

我正在尝试将实体保存到数据库,该实体具有复合主键

  1. 唯一标识符号
  2. 日期
  3. 一个布尔标志

我有一个用于提供上述功能的宁静 API。

我的 JPA 存储库接口和类:

@NoRepositoryBean
public interface customRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
  void refresh(T t);

  void merge(T t);

}

public class customRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
    implements customRepository<T, ID> {

  private final EntityManager entityManager;

  public customRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) {
    super(entityInformation, entityManager);
    this.entityManager = entityManager;
  }

  @Override
  @Transactional
  public void refresh(T t) {
    entityManager.refresh(t);
  }

  @Override
  @Transactional
  public void merge(T t) {
    entityManager.merge(t);
  }

我正在尝试使用以下方法合并我的服务类中的实体:

 myEntities.forEach(myEntity -> {
          customRepository.merge(myEntity);
        });

当我调用 API 来保存实体时,我看到了下面提到的异常。


    "stack_trace":"org.springframework.orm.ObjectOptimisticLockingFailureException: 
Batch update returned unexpected row count from update [0]; 
actual row count: 0; expected: 1; 
nested exception is org.hibernate.StaleStateException: 
Batch update returned unexpected row count from update [0]; 
actual row count: 0; expected: 1

jpa 的合并是否使用批量更新来持久化实体?而且由于我merge()通过迭代实体进行多次调用,为每个merge()调用创建的事务是否在下一次merge()调用之前突然结束?

标签: javaspringspring-mvcspring-bootspring-data-jpa

解决方案


推荐阅读