事务传播概况
主事务传播级别 REQUIRED
子事务传播级别 REQUIRES_NEW
实现效果
子事务中抛出异常,子事务回滚。主事务不受影响,代码逻辑正常执行
核心代码实现
主事务代码
@Service
public class UserService implements IUserService {
@Autowired
private UserMapper userMapper;
@Autowired
private ICourseService courseService;
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public String insert(String name, Integer age) {
try {
userMapper.update("update",14);
} catch (Exception e){
e.printStackTrace();
return "主事务异常";
}
try{
courseService.update("update",14);
}catch (Exception e){
e.printStackTrace();
return "子事务异常";
}
return "一切正常";
}
@Override
public String update(String name, Integer id) {
return "";
}
}
子事务核心代码
@Service
public class CourseService implements ICourseService {
@Autowired
private CourseMapper courseMapper;
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
public int insert(String name, Integer type) {
courseMapper.insert(name,type);
throw new RuntimeException("11");
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
public String update(String name, Integer id){
courseMapper.update(name,id);
throw new RuntimeException("11");
}
}