首页 > 解决方案 > SpringBoot JPA 存储库 saveAll 在 MongoDB 中引发写入冲突

问题描述

我有一个类似于下面给出的 Spring Boot 应用程序代码,它尝试在 MongoDB 中保存实体列表,但我收到此错误:

Exception in thread "Thread-20" org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 112 (WriteConflict): 'WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction.' on server 127.X.X.X:XXXXX. The full response is {"errorLabels": ["TransientTransactionError"]
Caused by: com.mongodb.MongoCommandException: Command failed with error 112 (WriteConflict): 'WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction.' on server 127.X.X.X:XXXXX. The full response is {"errorLabels": ["TransientTransactionError"]

那么,我应该怎么做才能避免这个错误/异常?

代码:

@Transactional
public synchronized void myMethod(List<MyEntity> myEntities) {
    saveEntities(myEntities);
}

public void saveEntities(List<MyEntity> myEntities) {
    myRepository.saveAll(myEntities);
}

标签: javamongodbspring-bootjpatransactions

解决方案


推荐阅读