更新localdatetime字段导致乐观锁定失败;嵌套的异常是org.hibernate.staleobjectstateexception

gt0wga4j  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(227)

我正试图使用@optimisticlocking更新库存实体,如下代码所示,但我得到以下错误
标识符为[1]的类[inventory]的对象:乐观锁定失败;嵌套异常为org.hibernate.staleobjectstateexception:行被另一个事务更新或删除(或未保存的值Map不正确):[inventory#1]
经过调查,如果我移除 inventory.setModifiedDate(LocalDateTime.now()); 线
如何解决这个问题?

@Getter
@Setter
@Entity
@DynamicUpdate
@OptimisticLocking(type = OptimisticLockType.DIRTY)
public class Inventory implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long amount;
    private LocalDateTime modifiedDate;
}

@Service
public class InventoryService {

    private final InventoryRepository inventoryRepository;

    public InventoryService(InventoryRepository inventoryRepository) {
        this.inventoryRepository = inventoryRepository;
    }

    @Transactional
    public void updateQuantity() {

        Inventory inventory = inventoryRepository.findById(1L).orElseThrow(ErrorHandler::entityNotFound);
        inventory.setAmount(inventory.getAmount() + 1000);
        inventory.setModifiedDate(LocalDateTime.now());
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题