在我的 Spring Boot 项目中,我实现了以下服务方法:
@Transactional
public boolean validateBoard(Board board) {
boolean result = false;
if (inProgress(board)) {
if (!canPlayWithCurrentBoard(board)) {
update(board, new Date(), Board.AFK);
throw new InvalidStateException(ErrorMessage.BOARD_TIMEOUT_REACHED);
}
if (!canSelectCards(board)) {
update(board, new Date(), Board.COMPLETED);
throw new InvalidStateException(ErrorMessage.ALL_BOARD_CARDS_ALREADY_SELECTED);
}
result = true;
}
return result;
}
在此方法中,我使用了另一种服务方法,称为 update
:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Board update(Board board, Date finishedDate, Integer status) {
board.setStatus(status);
board.setFinishedDate(finishedDate);
return boardRepository.save(board);
}
我需要在 update
方法中提交对数据库的更改,独立于在 validateBoard
方法中启动的所有者事务。现在,如果出现任何异常,任何更改都会回滚。
即使使用 @Transactional(propagation = Propagation.REQUIRES_NEW)
它也不起作用。
如何使用 Spring 正确执行此操作并允许嵌套事务?
原文由 alexanoid 发布,翻译遵循 CC BY-SA 4.0 许可协议
本文档涵盖了您的问题 - https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#transaction-declarative-annotations
但是,可以选择切换到 AspectJ 模式