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的报错查看数据库 并没有修改 表示事务已经开启成功 报错回滚