即便是出现的System.out.println(1/0);这种异常,,但是发生这个错误,你别撤销
如何设置发生错误不撤销
noRollbackFor:需要异常的类型noRollbackForClassName:需要异常的名称(更多用的是这个)
java.lang.ArithmeticException: / by zero
package com.chentianyu.service.impl;import com.chentianyu.mapper.AccountMapper;import com.chentianyu.pojo.Account;import com.chentianyu.service.AccountService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;@Service//业务逻辑层@Transactional(propagation = Propagation.REQUIRED/*事务的传播特性,增删改必走这个特性*/,noRollbackForClassName = "ArithmeticException")public class AccountServiceImpl implements AccountService {//但凡是业务逻辑层的实现类,一定会有数据访问层的对象@AutowiredAccountMapper accountMapper;@Overridepublic int insertAccount(Account account) {int num = 0;num = accountMapper.insertAccount(account);System.out.println("添加用户成功,num="+num);//手动抛出异常System.out.println(1/0);//出现错误的时候我们不希望数据插入进数据库return num;}}
告诉是算数异常别回滚
@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 | 张三 | 添加成功! |
这样子的处理就更加灵活了
