java - 函数@Transactionnal正常工作后如何以编程方式回滚?
问题描述
在@Transational 的某些功能起作用后,我尝试回滚
当由于 sql 和它的提交而出现错误时,回滚工作。
控制器
@RestController
@RequestMapping()
@Slf4j
@AllArgsConstructor
public class Controller {
private final MyServiceImpl myService;
@PostMapping("/truc")
public void truc() {
Entity ent = new Entity();
myService.createEntity(ent);
Entity2 ent2 = new Entity2();
myService.createEntity2(ent2);
boolean b = {some conditions};
if(b){
//to do flush
}
else{
//to do rollback to get initial state before createEntity()
}
}
}
我的服务实现
@Transactional
@Slf4j
@AllArgsConstructor
public class SiteServiceImpl {
//Repositories associed with entities extends JpaRepository
private RepoEntity repoEntity;
private RepoEntity2 repoEntity2;
@Transactional
protected void createEntity(Entity ent){
this.repoEntity.save(ent);
}
@Transactional
protected void createEntity2(Entity2 ent){
this.repoEntity2.save(ent);
}
}
我将能够以编程方式回滚和取消两个保存的实体。我不是 Spring 专家,也不知道该怎么做。可能与配置有关?
谢谢你的帮助。
解决方案
@Transactional
在Controller
水平上使用。RuntimeException
要触发回滚,请从控制器中抛出 。
如下所示:
public class Controller {
private final MyServiceImpl myService;
@Transactional
@PostMapping("/truc")
public void truc() {
Entity ent = new Entity();
myService.createEntity(ent);
Entity2 ent2 = new Entity2();
myService.createEntity2(ent2);
boolean b = {some conditions};
if(b){
//to do flush
}
else{
//This will trigger rollback
throw new RuntimeException("I want to rollback to cancel what I did in this method");
}
}
}
推荐阅读
- java - jackosn JSON 格式化程序在没有适当验证的情况下反序列化
- javascript - 如果 Toggle() 类隐藏,则取消选中单选按钮 如果切换类可见,请选中单选按钮
- swift - skpsmtpmessage 发送邮件功能无法正常工作?
- reactjs - 为 Material UI (React) 中的所有容器设置默认的 maxWidth
- javascript - Firebase ID 令牌已过期。从您的客户端应用程序获取新的 ID 令牌并重试(auth/id-token-expired)?
- javascript - ` fetch("/createpost", {...} ` 工作不正常
- css - Material-UI Grid:我可以将背景颜色仅应用于单元格,而不是它们之外的空白区域吗?
- python - 我应该在神经网络中转置特征或权重吗?
- javascript - 我怎样才能摆脱我的 js 代码中的 onclick,还有其他选择吗?
- python - MLModel 适用于 MultiArray 输出,但无法成功将输出更改为图像