java - Propagation REQUIRED 如何在 Spring Boot 中工作?
问题描述
我只是想了解 spring 中的事务传播:在我的项目中使用 jpa、postgres、验证器和 web starter。需要传播 说:
当这些逻辑事务之一回滚时,当前物理事务的所有逻辑事务都会回滚。
但是当我在insertUserKumar()中抛出异常时,它不应该按照文档将数据保存在数据库中,但它会被保存。
我的属性定义如下
logging.level.sql=debug
spring.datasource.generate_unique_name=false
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=dummy
spring.datasource.password=dummy
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.hikari.auto-commit=false
spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true
- 有人会说您可能错过了@EnableTransactionManagement我尝试过或不尝试过。但是有两条记录被持久化到数据库中。谁能帮我?
@Slf4j
@Component
@RequiredArgsConstructor
public class AppRunner implements CommandLineRunner {
private final UserRepository userRepository;
@Override
public void run(String... args) throws Exception {
insertUserBunty();// this transaction should fail but its getting persisted
}
@Transactional(propagation = Propagation.REQUIRED)
void insertUserBunty() {
User bunty = new User(null, "Bunty");
userRepository.save(bunty);
insertUserKumar();
}
@Transactional(propagation = Propagation.REQUIRED)
void insertUserKumar() {
User kumar = new User(null, "Kumar");
userRepository.save(kumar);
throw new RuntimeException("This will rollback both insert Bunty and Kumar");
}
}
解决方案
原因是@Transactional
当您从类中的另一个方法调用该方法时,它不起作用。原因是 Spring 处理事务特性的方式。它基本上由您的类的代理处理,因此@Transactional
注释仅在您的类外的方法调用该方法时才有效。在以下位置查看详细信息:
推荐阅读
- c# - 获取asp.net MVC中下拉列表和文本框的值
- wordpress - 如何以不同的方式为带有子页面的 WordPress 菜单项设置样式?
- python - 图中未显示边界框
- android - Chromecast 选项在 Android WebView 中不起作用
- opencl - 是否可以在 pyopencl 中运行 4 维工作项?
- php - Laravel Form::password 如果是只读的,则不显示值
- amazon-web-services - 使用 terraform 的 AWS 项目结构
- python - Paramiko/SFTP 系统 - 上传后无法打开一个文件
- java - 有关问题:查找链表的最后 N 个节点的总和
- android - 如何在按钮单击时更改位图图像