我正在编写一个很小的spring boot应用程序,没有任何与事务相关的特殊属性。我的REST控制器在存储库上调用save(myEntity)
。
何时进行数据库事务处理?
会被承诺
save
方法的一部分吗? (可能为时过早,以后可能会出现异常)示例代码dbtransaction/Application.java
:
package dbtransaction;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.UUID;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
@RequestMapping("/thing")
class ThingRestController {
private ThingRepository thingRepository;
public ThingRestController(ThingRepository thingRepository) {
this.thingRepository = thingRepository;
}
@RequestMapping(method = RequestMethod.GET)
public Thing createNew() {
return thingRepository.save(new Thing());
}
}
@Repository
interface ThingRepository extends JpaRepository<Thing, String> {
}
@Entity
class Thing {
@Id
public UUID uuid = UUID.randomUUID();
}
示例pom 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>
<artifactId>dbtransaction</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.23.1-GA</version>
</dependency>
</dependencies>
</project>
答案 0 :(得分:1)
何时提交取决于您的交易范围。在您提供的代码示例中,您没有指定任何事务范围,因此它将默认为您的存储库方法。它将在您致电thingRepository.save
之后提交。
请注意,JpaRepository
的默认实现是SimpleJpaRepository
,如果您查看该类,则会看到它用@Transactional
注释了其save方法。因此,这成为您交易的默认边界。您可以通过在外部方法上指定@Transactional
来轻松更改事务范围。