gpt4 book ai didi

java - @Transactional 不适用于 Spring Boot 和 JDBC

转载 作者:行者123 更新时间:2023-12-01 14:14:29 24 4
gpt4 key购买 nike

我的服务应该将数据保存到父和子数据库表,并在发生错误时回滚。我试过使用硬编码 RuntimeException 强制出错,并发现事务无论如何都会被提交。
我错过了什么?
我正在使用 Spring Boot 2,包括 spring-boot-starter-jdbc依赖性。

数据库是 Oracle 11g。

主要配置:

@SpringBootApplication
@EnableTransactionManagement
public class MyApplication extends SpringBootServletInitializer{

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}

public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

服务层:
    @Service
public class MyBean {

private final NamedParameterJdbcTemplate jdbcTemplate;
private final MyDAO myDao;

@Autowired
public MyBean (NamedParameterJdbcTemplate jdbcTemplate, MyDAO myDao) {
this.jdbcTemplate = jdbcTemplate;
this.myDao= myDao;
}

@Override
@Transactional
public void saveData(...){
myDao.saveData(jdbcTemplate, ...);
}

}

道:
public void saveData(jdbcTemplate, ...){
saveDataInParentDatatable(jdbcTemplate, ...);
saveDataInChildDatatable(jdbcTemplate, ...);
}
private void saveDataInChildDatatable(jdbcTemplate, ...){
throw new RuntimeException();
}

最佳答案

我遇到了类似的问题。我假设您在 MyBean 的另一个方法中调用 MyBean.saveData 方法。

经过多次搜索、尝试和失败,我找到了这个链接:http://ignaciosuay.com/why-is-spring-ignoring-transactional/

其中解释了当被调用的方法在调用它的同一个类中时,@Transactional 注释被忽略。 Spring explanation因为它是:

“In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. @PostConstruct.”



所以我创建了另一个类来封装我的 DAO 方法调用,而是使用它的方法并且它起作用了。

所以对于这种情况,它可能是这样的:

我的 bean :
@Service
public class MyBean {

MyBean2 bean2;

public void saveData(...){
bean2.saveData(jdbcTemplate, ...);
}
}

我的 bean 2:
@Service
public class MyBean2 {

private final NamedParameterJdbcTemplate jdbcTemplate;
private final MyDAO myDao;

@Autowired
public MyBean2 (NamedParameterJdbcTemplate jdbcTemplate, MyDAO myDao) {
this.jdbcTemplate = jdbcTemplate;
this.myDao= myDao;
}

@Override
@Transactional
public void saveData(...){
myDao.saveData(jdbcTemplate, ...);
}
}

关于java - @Transactional 不适用于 Spring Boot 和 JDBC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50639361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com