springboot配置事务@Transactional

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hju22/article/details/88235703

在方法上加上注解@Transactional,就可以管理事务了

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    //插入用户
    @Transactional
    public void insert(String name,int age){
        User user=new User();
        user.setName(name);
        user.setAge(age);
        userMapper.insert(user); //向数据库插入一条记录
        throw new RuntimeException("###发生运行时异常###"); //手动模拟抛出异常
    }

}

抛出异常后,事务会自动回滚,数据不会插入数据库。

猜你喜欢

转载自blog.csdn.net/hju22/article/details/88235703