SpringBoot 使用事務非常簡單,底層依然采用的是Spring本身提供的事務管理
• 在入口類中使用注解 @EnableTransactionManagement 開啟事務支持
• 在訪問數(shù)據(jù)庫的Service方法上添加注解 @Transactional 即可
案例思路
通過SpringBoot +MyBatis實現(xiàn)對數(shù)據(jù)庫學生表的更新操作,在service層的方法中構建異常,查看事務是否生效;
項目名稱:012-springboot-web-mybatis-transacation
該項目是在011的基礎上添加新增方法,在新增方法中進行案例的演示。
1.在StudentController中添加更新學生的方法
@Controller
public class SpringBootController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/springBoot/update")
public @ResponseBody Object update() {
Student student = new Student();
student.setId(1);
student.setName("Mark");
student.setAge(100);
int updateCount = studentService.update(student);
return updateCount;
}
}
2.在StudentService接口中添加更新學生方法
public interface StudentService {
/**
* 根據(jù)學生標識更新學生信息
* @param student
* @return
*/
int update(Student student);
}
3.在StudentServiceImpl接口實現(xiàn)類中對更新學生方法進行實現(xiàn),并構建一個異常,同時在該方法上加@Transactional注解
@Override
@Transactional //添加此注解說明該方法添加的事務管理
public int update(Student student) {
int updateCount = studentMapper.updateByPrimaryKeySelective(student);
System.out.println("更新結果:" + updateCount);
//在此構造一個除數(shù)為0的異常,測試事務是否起作用
int a = 10/0;
return updateCount;
}
4.在Application類上加@EnableTransactionManagement開啟事務支持
@EnableTransactionManagement可選,但是@Service必須添加事務才生效
@SpringBootApplication
@EnableTransactionManagement //SpringBoot開啟事務的支持
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5.啟動Application,通過瀏覽器訪問進行測試
瀏覽器
控制臺
數(shù)據(jù)庫表
通過以上結果,說明事務起作用了。
6.注釋掉StudentServiceImpl上的@Transactional測試
數(shù)據(jù)庫的數(shù)據(jù)被更新