【发布时间】:2020-03-27 11:19:32
【问题描述】:
有人知道如何在 Spring Data REST 中处理同一事务中的多个实体更新吗?使用 @Transactional 注释可以在 Spring 控制器方法中处理相同的事情。如果我是正确的,Spring Data REST 在单独的事务中执行每个执行事件。因此无法以适当的方式处理多个实体更新。
我在同一事务中更新 2 个实体(ABC 和 PQR)以及在 PQR 实体失败时回滚 ABC 实体时遇到问题。
// ABC repository
@RepositoryRestResource
public interface ABCEntityRepository extends MongoRepository<ABC, String> {
}
// PQR repository
@RepositoryRestResource
public interface PQREntityRepository extends MongoRepository<PQR, String> {
}
// ABC repository handler
@RepositoryEventHandler
public class ABCEventHandler {
@Autowired
private PQREntityRepository pqrEntityRepository;
@HandleBeforeSave
public void handleABCBeforeSave(ABC abc) {
log.debug("before saving ABC...");
}
@HandleAfterSave
public void handleABCAfterSave(ABC abc) {
List<PQR> pqrList = pqrEntityRepository.findById(abc.getPqrId());
if (pqrList != null && !pqrList.isEmpty()) {
pqrList.forEach(pqr -> {
// update PQR objects
}
}
// expect to fail this transaction
pqrEntityRepository.saveAll(pqrList);
}
}
由于@HandleAfterSave方法在单独的事务中执行,调用HandleAfterSave方法意味着ABC实体更新已经完成,因此不能回滚。有什么建议来处理这个吗?
【问题讨论】:
标签: spring-data-mongodb spring-data-rest