Spring Data:在update中返回null将回滚事务

时间:2017-09-23 03:09:25

标签: java spring spring-data

在我的代码中,update方法可能会返回null,并且会影响调用此方法的事务。

我知道只抛出运行时异常或用户指定已检查的异常会触发回滚动作,那么返回null也会触发它吗?

服务1

public class Service1 {

    @Autowired
    private Service2 service2;

    @Autowried
    private Service1Repository service1Repository;

    @Transactional
    public Entity1 update(Entity1 entity) {
        service1Repository.update(entity);

        // if this method return null, above update will rollback. Otherwise, it will be executed success.
        service2.update(entity.getId());

        return entity;
    }
}

服务2:

public class Service2 {
    @Autowired
    private Service2Repository service2Repository;

    @Transactional
    public Entity2 update(Integer id) {
        Entity2 entity = service2Repository.findOne(id);

        // No need to update HIDDEN status entity
        if (Status.HIDDEN.equals(entity.getStatus())) {
            return null;
        }

        entity.setOtherAttribute("xyz");
        service2Repository.update(entity);

        return entity;
    }
}

1 个答案:

答案 0 :(得分:0)

null方法返回Service2.update()将不会回滚数据库事务,因为这是正常的代码执行。

另外,如Spring documentation中所述:

  

任何RuntimeException都会触发回滚,而任何已检查的Exception都不会。

相关问题