A possibility of invalid springboot transaction


When using Springboot to build a web project, use @Transactional annotation for transaction management. When the service layer method does not use public decoration, the transaction will be invalid:

Dao Layer code

package com.iotek.myspringboot.myspringboot;

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

Import java.util.List;

/**
 * dao layer inherits JpaRepository class
 */
Public interface StudentRepository extends JpaRepository<Student, Integer> {
    List<Student> findByName(String name);
}

service layer code fragment

/**
     * Transaction test (add two records, manually throw an exception in the middle, test ACID)
     */
    @Transactional
    Public void insertTwo() {
        Student s1 = new Student();
        s1.setName("aaa");
        s1.setScore(100d);
        studentRepository.save(s1);

        Int i = 100 / 0; / / manually throw the exception to verify the effectiveness of transaction management

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

controller layer code

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

test process

一, controller test method does not use public modifier

do not use public decoration: 

不使用public修饰

MySQL database table content (before request) :

MySQL数据库表内容

Executive request: 

执行请求

 After executing the database content: 

这里写图片描述

二, controller test method using public modifier

 using public decoration: 

使用public修饰

Execution request: 

执行请求

 Database content after execution:

执行之后数据库内容