首页 > 解决方案 > 函数@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 专家,也不知道该怎么做。可能与配置有关?

谢谢你的帮助。

标签: javaspringspring-data-jpa

解决方案


@TransactionalController水平上使用。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");
        }
    }
}

推荐阅读