1.入口文件中开启事务(可无)

@EnableTransactionManagement // 开启事务,可不写,默认开启
package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement // 开启事务,可不写,默认开启

@MapperScan("com.example.demo.mapper") // 开启扫描mapper接口的包以及子目录
public class DemoApplication {

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

}

2.在执行添加或者更新的业务操作开启事务

@Transactional
package com.example.demo.service;

import com.example.demo.model.Student;

public interface StudentService {

/**
* 根据学生标识获取学生详情
* @param id
* @return
*/
Student queryStudentById(Integer id);

/**
* 根据学生ID修改学生信息
* @param student
* @return
*/
int updateStudentById(Student student);
}
package com.example.demo.service.impl;

import com.example.demo.mapper.StudentMapper;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl implements StudentService {

@Autowired
private StudentMapper studentMapper;

@Override
public Student queryStudentById(Integer id) {
return studentMapper.selectByPrimaryKey(id);
}

@Transactional
@Override
public int updateStudentById(Student student) {
int i = studentMapper.updateByPrimaryKeySelective(student);
int a = 10 / 0;

return i;
}
}