1. 程式人生 > >springboot事務失效的一種可能

springboot事務失效的一種可能


使用Springboot搭建web專案時,使用@Transactional註解進行事務管理,當service層方法沒有使用public修飾時,事務處理將會失效:

Dao層程式碼

package com.iotek.myspringboot.myspringboot;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * dao層繼承JpaRepository類
 */
public interface StudentRepository extends JpaRepository<Student, Integer> {
    List<Student> findByName(String name);
}

service層程式碼片段

/**
     * 事務測試(新增兩條記錄,中間手動丟擲一個異常,測試ACID)
     */
    @Transactional
    public void insertTwo() {
        Student s1 = new Student();
        s1.setName("aaa");
        s1.setScore(100d);
        studentRepository.save(s1);

        int i = 100 / 0;//手動丟擲異常驗證事務管理的有效性

        Student s2 = new Student();
        s2.setName("bbb");
        s2.setScore(666d);
        studentRepository.save(s2);
    }

controller層程式碼

@GetMapping(value = "/insertTwo")
    public void insertTwo() {
        studentService.insertTwo();
    }

測試過程

一、 controller的測試方法不使用public修飾符

不使用public修飾:

不使用public修飾

 MySQL資料庫表內容(請求之前):

MySQL資料庫表內容

執行請求:

執行請求

執行之後資料庫內容:

這裡寫圖片描述

二、 controller的測試方法使用public修飾符

使用public修飾:

使用public修飾

執行請求:

執行請求

執行之後資料庫內容:

執行之後資料庫內容