- 增加@EnableTransactionManagement注解
package com.yunchuang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableScheduling
@ServletComponentScan
@EnableTransactionManagement
public class YunchuangApplication {
public static void main(String[] args) {
SpringApplication.run(YunchuangApplication.class, args);
}
}
2.在service的實(shí)現(xiàn)類或者方法上添加下面這個(gè)注解即可.事務(wù)管理器的配置在多數(shù)據(jù)源那篇里已經(jīng)配置過了.默認(rèn)情況下只有RuntimeException才回滾,為了讓Exception也回滾,增加了 rollbackFor = Exception.class.
@Transactional(value = "masterTransactionManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
3.測試:
在service里添加一個(gè)方法,controller里添加一個(gè)方法,訪問這個(gè)方法,可以發(fā)現(xiàn),數(shù)據(jù)沒有插入成功.
@Override
public void addTest() throws Exception {
Leave leave = new Leave();
leave.setDepartment("事務(wù)部門4");
leave.setName("事姓名4");
leaveDao.add(leave);
if (leaveDao.loadById(3727) != null) {
throw new Exception("事務(wù)異常4");
}
}
@GetMapping("/test")
@ResponseBody
public String test() throws Exception {
leaveService.addTest();
return "123";
}