我有 2 个存储库 - 每个存储库都有不同对象的保存方法。 我想将这两个方法作为事务执行,这意味着如果其中一个方法失败,事务将回滚。 (我认为这就是交易的意义)。
这是我的代码:
@Repository
public class BananaRep {
private JdbcTemplate jdbc;
@Autowired
public BananaRep(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public void saveBanana(Banana banana) {
jdbc.update("insert into ......", ...);
}
}
@Repository
public class TomatoRep {
private JdbcTemplate jdbc;
@Autowired
public TomatoRep(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public void saveTomato(Tomato tomato) {
jdbc.update("insert into ... ", ....);
}
}
@RestController
public class MixController {
@Autowired
BananaRep bananaRep;
@Autowired
TomatoRep tomatoRep;
@Transactional
@RequestMapping(value="/mix", method= RequestMethod.GET)
public Car mix() {
Banana banana = new Banana(....);
bananaRep.saveBanana(banana );
Tomato tomato= new Tomato(...);
tomatoRep.saveTomato(tomato);
return banana;
}
}
我的构建:
buildscript {
ext {
springBootVersion = '2.0.0.M2'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-jersey')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('mysql:mysql-connector-java')
}
为了测试它,我更改了 Tomato 表中一个数据库列的名称,因此在我的 Controller 中 saveTomato(tomato) 方法将失败。我希望如果发生这种情况,保存的香蕉将被回滚。我认为它应该像 @Transactional 方法注释一样工作,但我错了。
那么如何实现我的目标呢?
最佳答案
事务控制应该放在服务业务处理层
关于java - 如何在Spring中使用@Transactional实现真正的事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45321002/