Spring 引导 + Spring 数据 JPA + 事务无法正常工作
Spring Boot + Spring Data JPA + Transactions not working properly
我使用 1.2.0 版本和 spring-boot-starter-data-jpa 创建了一个 Spring 引导应用程序,我正在使用 MySQL。
我已在 application.properties 文件中正确配置我的 MySQL 属性。
我有一个简单的 JPA 实体、Spring 数据 JPA 存储库和一个服务,如下所示:
@Entity
class Person
{
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
//setters & getters
}
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer>{
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
class PersonService
{
@Autowired PersonRepository personRepository;
@Transactional
void save(List<Person> persons){
for (Person person : persons) {
if("xxx".equals(person.getName())){
throw new RuntimeException("boooom!!!");
}
personRepository.save(person);
}
}
}
我有以下 JUnit 测试:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
@Autowired
PersonService personService;
@Test
public void test_logging() {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person(null,"abcd"));
persons.add(new Person(null,"xyz"));
persons.add(new Person(null,"xxx"));
persons.add(new Person(null,"pqr"));
personService.save(persons);
}
}
这里的期望是它不应该向 PERSON table 中插入任何记录,因为它会在插入第三人称对象时抛出异常。
但它没有回滚,前 2 条记录正在插入和提交。
然后我想到了赶紧用JPA EntityManager试试。
@PersistenceContext
private EntityManager em;
em.save(person);
然后我得到 javax.persistence.TransactionRequiredException:没有可用的事务性 EntityManager 异常。
谷歌搜索一段时间后,我遇到了关于同一主题的这个 JIRA 线程 https://jira.spring.io/browse/SPR-11923。
然后我将 Spring 引导版本更新为 1.1.2 以获得比 4.0.6[= 更早的 Spring 版本56=].
然后 em.save(person) 按预期工作并且事务工作正常(意味着它在发生 RuntimeException 时回滚所有数据库插入)。
但即使使用 Spring 4.0.5 + Spring Data JPA 1.6.0 版本事务在 personRepository.save(person) 代替 em.persist(person).
似乎 Spring Data JPA 存储库正在提交事务。
我错过了什么?如何使服务级别 @Transactional 注释起作用?
PS:
Maven pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sivalabs</groupId>
<artifactId>springboot-data-jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-data-jpa</name>
<description>Spring Boot Hello World</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.0.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.sivalabs.springboot.Application</start-class>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
Application.java
@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
将事务注释更改为
@Transactional(rollbackFor=Exception.class)
我用 SpringBoot v1.2.0 和 v1.5.2 测试了这个,一切都按预期工作,你不需要使用实体管理器,也不需要 @Transactional(rollbackFor=Exception.class).
我看不出你配置错误的部分,乍一看一切都很好,所以我只是将我的所有配置作为参考发布,其中包含更多更新的注释和 H2 嵌入式内存数据库:
application.properties
# Embedded memory database
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:h2:~/test;AUTO_SERVER=TRUE
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo</groupId>
<artifactId>jpaDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
</project>
Person.java
@Entity
public class Person
{
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer id;
private String name;
public Person() {}
public Person(String name) {this.name = name;}
public Integer getId() {return id;}
public void setId(Integer id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
PersonRepository.java
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {}
PersonService.java
@Service
public class PersonService
{
@Autowired
PersonRepository personRepository;
@Transactional
public void saveTransactional(List<Person> persons){
savePersons(persons);
}
public void saveNonTransactional(List<Person> persons){
savePersons(persons);
}
private void savePersons(List<Person> persons){
for (Person person : persons) {
if("xxx".equals(person.getName())){
throw new RuntimeException("boooom!!!");
}
personRepository.save(person);
}
}
}
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
PersonServiceTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
PersonService personService;
@Autowired
PersonRepository personRepository;
@Test
public void person_table_size_1() {
List<Person> persons = getPersons();
try {personService.saveNonTransactional(persons);}
catch (RuntimeException e) {}
List<Person> personsOnDB = personRepository.findAll();
assertEquals(1, personsOnDB.size());
}
@Test
public void person_table_size_0() {
List<Person> persons = getPersons();
try {personService.saveTransactional(persons);}
catch (RuntimeException e) {}
List<Person> personsOnDB = personRepository.findAll();
assertEquals(0, personsOnDB.size());
}
public List<Person> getPersons(){
List<Person> persons = new ArrayList() {{
add(new Person("aaa"));
add(new Person("xxx"));
add(new Person("sss"));
}};
return persons;
}
}
*每次测试都会清除并重新初始化数据库,以便我们始终根据已知状态进行验证
来自@m-deinum 的:
Make your PersonService public
as well as the method you are calling.
这似乎对一些用户起到了作用。同样的事情也包含在 this answer, citing manual saying:
When using proxies, you should apply the @Transactional annotation
only to methods with public visibility. If you do annotate protected,
private or package-visible methods with the @Transactional annotation,
no error is raised, but the annotated method does not exhibit the
configured transactional settings. Consider the use of AspectJ (see
below) if you need to annotate non-public methods.
我使用 1.2.0 版本和 spring-boot-starter-data-jpa 创建了一个 Spring 引导应用程序,我正在使用 MySQL。 我已在 application.properties 文件中正确配置我的 MySQL 属性。
我有一个简单的 JPA 实体、Spring 数据 JPA 存储库和一个服务,如下所示:
@Entity
class Person
{
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
//setters & getters
}
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer>{
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
class PersonService
{
@Autowired PersonRepository personRepository;
@Transactional
void save(List<Person> persons){
for (Person person : persons) {
if("xxx".equals(person.getName())){
throw new RuntimeException("boooom!!!");
}
personRepository.save(person);
}
}
}
我有以下 JUnit 测试:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
@Autowired
PersonService personService;
@Test
public void test_logging() {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person(null,"abcd"));
persons.add(new Person(null,"xyz"));
persons.add(new Person(null,"xxx"));
persons.add(new Person(null,"pqr"));
personService.save(persons);
}
}
这里的期望是它不应该向 PERSON table 中插入任何记录,因为它会在插入第三人称对象时抛出异常。 但它没有回滚,前 2 条记录正在插入和提交。
然后我想到了赶紧用JPA EntityManager试试。
@PersistenceContext
private EntityManager em;
em.save(person);
然后我得到 javax.persistence.TransactionRequiredException:没有可用的事务性 EntityManager 异常。
谷歌搜索一段时间后,我遇到了关于同一主题的这个 JIRA 线程 https://jira.spring.io/browse/SPR-11923。
然后我将 Spring 引导版本更新为 1.1.2 以获得比 4.0.6[= 更早的 Spring 版本56=].
然后 em.save(person) 按预期工作并且事务工作正常(意味着它在发生 RuntimeException 时回滚所有数据库插入)。
但即使使用 Spring 4.0.5 + Spring Data JPA 1.6.0 版本事务在 personRepository.save(person) 代替 em.persist(person).
似乎 Spring Data JPA 存储库正在提交事务。
我错过了什么?如何使服务级别 @Transactional 注释起作用?
PS:
Maven pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sivalabs</groupId>
<artifactId>springboot-data-jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-data-jpa</name>
<description>Spring Boot Hello World</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.0.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.sivalabs.springboot.Application</start-class>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
Application.java
@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
将事务注释更改为 @Transactional(rollbackFor=Exception.class)
我用 SpringBoot v1.2.0 和 v1.5.2 测试了这个,一切都按预期工作,你不需要使用实体管理器,也不需要 @Transactional(rollbackFor=Exception.class).
我看不出你配置错误的部分,乍一看一切都很好,所以我只是将我的所有配置作为参考发布,其中包含更多更新的注释和 H2 嵌入式内存数据库:
application.properties
# Embedded memory database
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:h2:~/test;AUTO_SERVER=TRUE
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo</groupId>
<artifactId>jpaDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
</project>
Person.java
@Entity
public class Person
{
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer id;
private String name;
public Person() {}
public Person(String name) {this.name = name;}
public Integer getId() {return id;}
public void setId(Integer id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
PersonRepository.java
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {}
PersonService.java
@Service
public class PersonService
{
@Autowired
PersonRepository personRepository;
@Transactional
public void saveTransactional(List<Person> persons){
savePersons(persons);
}
public void saveNonTransactional(List<Person> persons){
savePersons(persons);
}
private void savePersons(List<Person> persons){
for (Person person : persons) {
if("xxx".equals(person.getName())){
throw new RuntimeException("boooom!!!");
}
personRepository.save(person);
}
}
}
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
PersonServiceTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
PersonService personService;
@Autowired
PersonRepository personRepository;
@Test
public void person_table_size_1() {
List<Person> persons = getPersons();
try {personService.saveNonTransactional(persons);}
catch (RuntimeException e) {}
List<Person> personsOnDB = personRepository.findAll();
assertEquals(1, personsOnDB.size());
}
@Test
public void person_table_size_0() {
List<Person> persons = getPersons();
try {personService.saveTransactional(persons);}
catch (RuntimeException e) {}
List<Person> personsOnDB = personRepository.findAll();
assertEquals(0, personsOnDB.size());
}
public List<Person> getPersons(){
List<Person> persons = new ArrayList() {{
add(new Person("aaa"));
add(new Person("xxx"));
add(new Person("sss"));
}};
return persons;
}
}
*每次测试都会清除并重新初始化数据库,以便我们始终根据已知状态进行验证
来自@m-deinum 的
Make your PersonService
public
as well as the method you are calling.
这似乎对一些用户起到了作用。同样的事情也包含在 this answer, citing manual saying:
When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.