Transactional注解的rollbackFor属性

Transactional注解的rollbackFor属性,此属性是指定程序中自定义检查异常的回滚情况,如果rollbackFor属性未指定自定义检查异常当发生自定义检查异常时事物是不会回滚的,只有指定了的自定义检查异常事务才会回滚

测试案例

持久层使用的是JPA,save()是JPA原生方法,没有实现,测试案例从service层开始
Service

@Service
public class UserService {

    @Autowired
    private UserRepo userDao;

    @Transactional(rollbackFor = CommonException.class)
    public void add(UserEntity entity) throws CommonException {
        userDao.save(entity);
        throw new CommonException("事物回滚测试");
    }

    @Transactional
    public void save(UserEntity entity) throws CommonException {
        userDao.save(entity);
        throw new CommonException("事物回滚测试");
    }

}

Controller

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public void add() {
        UserEntity entity = new UserEntity();
        try {
            entity.setUserAge(19);
            entity.setUsername("test-name-yes");
            entity.setPassword("test-password-yes");
            entity.setUserSex(SexType.BOY);
            entity.setPhone("test-phone-yes");
            userService.add(entity);
        } catch (CommonException e) {
            System.out.println("rollbackFor携带自定义异常");
        }
    }

    @PostMapping("/save")
    public void save() {
        UserEntity entity = new UserEntity();
        entity.setUserAge(26);
        entity.setUsername("test-name-no");
        entity.setPassword("test-password-no");
        entity.setUserSex(SexType.BOY);
        entity.setPhone("test-phone-no");
        try {
            userService.save(entity);
        } catch (CommonException e) {
            System.out.println("rollbackFo不携带自定义异常");
        }
    }
}

调用两个接口查看数据库中内容为:add接口未成功插入数据到数据库,save接口成功插入数据到数据库
注意rollbackFor属性就算未指定运行时异常,当发生运行时异常时事务也会回滚

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值