即便是出现的System.out.println(1/0);这种异常,,但是发生这个错误,你别撤销

    如何设置发生错误不撤销

    • noRollbackFor:需要异常的类型
    • noRollbackForClassName:需要异常的名称(更多用的是这个)
    1. java.lang.ArithmeticException: / by zero
    1. package com.chentianyu.service.impl;
    2. import com.chentianyu.mapper.AccountMapper;
    3. import com.chentianyu.pojo.Account;
    4. import com.chentianyu.service.AccountService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import org.springframework.transaction.annotation.Propagation;
    8. import org.springframework.transaction.annotation.Transactional;
    9. @Service//业务逻辑层
    10. @Transactional(propagation = Propagation.REQUIRED/*事务的传播特性,增删改必走这个特性*/,
    11. noRollbackForClassName = "ArithmeticException")
    12. public class AccountServiceImpl implements AccountService {
    13. //但凡是业务逻辑层的实现类,一定会有数据访问层的对象
    14. @Autowired
    15. AccountMapper accountMapper;
    16. @Override
    17. public int insertAccount(Account account) {
    18. int num = 0;
    19. num = accountMapper.insertAccount(account);
    20. System.out.println("添加用户成功,num="+num);
    21. //手动抛出异常
    22. System.out.println(1/0);//出现错误的时候我们不希望数据插入进数据库
    23. return num;
    24. }
    25. }

    告诉是算数异常别回滚

    @Test
    public void test02(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext_service.xml");
        AccountService accountService = (AccountService) ac.getBean("accountServiceImpl");
        System.out.println(accountService.getClass());
        accountService.insertAccount(new Account(100,"张三","添加成功!"));
    }
    

    虽然还是异常了,但是数据库中还是添加进了数据

    aid aname acontent
    100 张三 添加成功!

    这样子的处理就更加灵活了