springboot 学习笔记(六)

1.springboot事务的开启

1.首先在主main类上添加开启事务的注解@EnableTransactionManagement

@SpringBootApplication
@MapperScan("com.example.demo.mapper")
@EnableTransactionManagement
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

2.在service上开启事务注解@Transactional

StudentService

public interface StudentService {

    int update();
}

StudentImpl

@Service
public class StudentImpl implements StudentService {


    @Autowired
    private StudentMapper studentMapper;

    @Transactional
    @Override
    public int update() {
        Student student = new Student();
        student.setName("123");
        student.setAddress("武汉");
        int update = studentMapper.updateByPrimaryKey(student);
        System.out.println(update);
        int i= 10/ 0;
        return update;
    }

}

这里studentMapper.updateByPrimaryKey是由mybatis插件自动生成的修改方法

MybatisController

@RestController
public class MybatisController {
    
    @Autowired
    private StudentService studentService;
   @RequestMapping("/update")
    public Object update(){
        return studentService.update();
   }
}

此时运行主main类 在浏览器上输入对应的路径就可以在控制台得到输出1 以及by zero的报错查看数据库 并没有修改 表示事务已经开启成功 报错回滚

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值