8.spring boot 事務配置

  1. 增加@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";
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容