使用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修饰:
MySQL数据库表内容(请求之前):
执行请求:
执行之后数据库内容:
二、 controller的测试方法使用public修饰符
使用public修饰:
执行请求:
执行之后数据库内容: