【Java技术总结】Spring事务失效总结

  1. 事务方法必须是public,private、protected、default都会失效。
@Service
public class UserService {
    @Transactional
    private void add(UserModel userModel) {
        saveData(userModel);
        updateData(userModel);
    }
}
  1. 被static和final修饰的方法会失效。
    因为事务底层使用了AOP,也就是通过JDK或者CG lib动态代理生成代理类,在代理类中实现的事务功能,被这两个修饰就会导致代理类无法重写该方法而添加事务功能
@Service
public class UserService {
    @Transactional
    private final void add(UserModel userModel) {
        saveData(userModel);
        updateData(userModel);
    }
}
  1. 方法内部调用
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    
    public void add(UserModel userModel) {
        userMapper.insertUser(userModel);
        updateStatus(userModel);
    }
    
    @Transactional
    private void add(UserModel userModel) {
        saveData(userModel);
        updateData(userModel);
    }
}

如果有这样的场景,可以采用以下方法解决:

  • 重新建一个类,让事务方法与调用方法分开在两个类
    事务,被调用方法类注入进调用类
@Service
public class ServiceA {

    @Autowired
    private ServiceB serviceB;

    public void save(User user) {
        queryData1();
        queryData2();
        serviceB.doSave(user);
    }
}

@Service
public class ServiceB {

    @Transactional(rollbackFor = Exception.class)
    public void doSave(User user) {
        addData1();
        updateData2();
    }
}
  • 自己注入自己,不会有循环依赖问题,但是有坑
@Service
public class ServiceA {

    @Autowired
    private ServiceA serviceA;

    public void save(User user) {
        queryData1();
        queryData2();
        serviceA.doSave(user);
    }
    @Transactional(rollbackFor = Exception.class)
    public void doSave(User user) {
        addData1();
        updateData2();
    }
}
  • 上面的改进版,使用AOPContext.currentProxy()来获取代理对象实现相同功能
@Service
public class ServiceA {

    public void save(User user) {
        queryData1();
        queryData2();
        ((ServiceA)AopContext.currentProxy()).doSave(user);
    }
    @Transactional(rollbackFor = Exception.class)
    public void doSave(User user) {
        addData1();
        updateData2();
    }
}
  1. 未被Spring管理,比如没加@Service注解
//@Service
public class UserService {
    @Transactional
    public void add(UserModel userModel) {
        saveData(userModel);
        updateData(userModel);
    }
}
  1. 多线程调用
    由于Spring事务是通过数据库连接来实现的,每个线程保存了一个map用来记录当前数据库连接,只有拥有同一个数据库连接才能同时的提交和回滚,不同线程拿到的数据库连接不同,是不同事务
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;

    @Transactional
    public void add(UserModel userModel) throws Exception {
        userMapper.insertUser(userModel);
        new Thread(() -> {
            roleService.doOtherThing();
        }).start();
    }
}
@Service
public class RoleService {
    
    @Transactional
    public void doOtherThing() {
        System.out.println("保存role表数据");
    }
}
  1. 表不支持事务MyISAM引擎不支持事务
  2. 未开启事务Spring老项目需要手动配置applicationContext.xml里配置开启事务,SpringBoot项目配置数据源会默认开启
  3. 错误的传播特性
    @Transactional注解指定了propagation属性,如果不是7种传播属性中的REQUIRED、REQUIRESNEW、NESTED就会当前事务失效,下面的就会失效
@Service
public class UserService {
    @Transactional(propagation = Propagation.NEVER)
    public void add(UserModel userModel) {
        saveData(userModel);
        updateData(userModel);
    }
}
  1. 自己try…catch了异常,事务不会回滚
    想要Spring正常回滚,必须抛出Spring能够处理的异常,没抛异常,Spring会认为程序正常处理
@Slf4j
@Service
public class UserService {
    @Transactional
    public void add(UserModel userModel) {
        try {
            saveData(userModel);
            updateData(userModel);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }
}
  1. 手动抛了别的异常事务也不会回滚
    比如下面手动抛了Exception异常也不会回滚,因为Spring默认只处理RuntimeException和Error,对于普通的Exception不会回滚
@Slf4j
@Service
public class UserService {
    @Transactional
    public void add(UserModel userModel) throws Exception {
        try {
            saveData(userModel);
            updateData(userModel);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new Exception(e);
        }
    }
}
  1. 自定义了回滚异常
    比如保存和更新数据时,程序抛了SqlException、DuplicateKeyException异常就会因为不属于自定义异常而导致不回滚
    一般程序出现异常应当回滚,所以设定该参数为Exception或Throwable
@Slf4j
@Service
public class UserService {
    @Transactional(rollbackFor = BusinessException.class)
    public void add(UserModel userModel) throws Exception {
        saveData(userModel);
        updateData(userModel);
    }
}
  1. 嵌套事务回滚多了
    嵌套事务中只想回滚一部分事务,并不想回滚全部事务,子事务必须使用传播特性NESTED,并且上级调用时要捕获异常,因为不捕获异常就会继续上抛导致整个事务回滚
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Transactional
    public void add(UserModel userModel) throws Exception {
        userMapper.insertUser(userModel);
        roleService.doOtherThing();
    }
}

@Service
public  class RoleService {
    @Transactional(propagation = Propagation.NESTED)
    public void doOtherThing() {
        System.out.println("保存role表数据");
    }
}

这样会回滚全部,下面是改进:

public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Transactional
    public void add(UserModel userModel) throws Exception {
        userMapper.insertUser(userModel);
        try {
            roleService.doOtherThing();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }
}

@Service
public  class RoleService {
    @Transactional(propagation = Propagation.NESTED)
    public void doOtherThing() {
        System.out.println("保存role表数据");
    }
}
posted @ 2022-10-26 00:24  求道之愚者  阅读(907)  评论(0)    收藏  举报