在上个整合Myybatis项目基础上进行进一步的更改
事务是一个完整的业务,只跟SQL的增、删、改有关。
- 修改Controller类添加一个更新的方法
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/student/{id}")
public Student queryStudentById(@PathVariable Integer id) {
return studentService.queryStudentById(id);
}
@GetMapping("/update")
public String update(Integer id, String name) {
Student student = new Student();
student.setId(id);
student.setName(name);
int updateCount = studentService.update(student);
return "修改学生编号" + id + "的姓名结果:" + name;
}
}
- 修改Service接口和实现类
// 接口
public interface StudentService {
Student queryStudentById(Integer id);
int update(Student student);
}
// 实现类
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student queryStudentById(Integer id) {
return studentMapper.selectByPrimaryKey(id);
}
@Transactional
@Override
public int update(Student student) {
int i = studentMapper.updateByPrimaryKey(student);
//这段代码肯定报错, 数据库不应该更改,修过添加支持注解
int a = 10/0;
return i;
}
}
- 实现事务需要在支持事务的方法上添加
@Transactional
注解- 如果是springboot1.x需要的启动类上添加
@EnableTransactionManagement
开启事务
@SpringBootApplication
@EnableTransactionManagement // 开启事务(springboot1.x需要加, 事务才会生效)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}