- 增加@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的实现类或者方法上添加下面这个注解即可.事务管理器的配置在多数据源那篇里已经配置过了.默认情况下只有RuntimeException才回滚,为了让Exception也回滚,增加了 rollbackFor = Exception.class.
@Transactional(value = "masterTransactionManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
3.测试:
在service里添加一个方法,controller里添加一个方法,访问这个方法,可以发现,数据没有插入成功.
@Override
public void addTest() throws Exception {
Leave leave = new Leave();
leave.setDepartment("事务部门4");
leave.setName("事姓名4");
leaveDao.add(leave);
if (leaveDao.loadById(3727) != null) {
throw new Exception("事务异常4");
}
}
@GetMapping("/test")
@ResponseBody
public String test() throws Exception {
leaveService.addTest();
return "123";
}