java - JDBC Spring数据@Transactional不起作用
问题描述
我正在使用 springboot 和 spring-data-jdbc。
我写了这个存储库类
@Repository
@Transactional(rollbackFor = Exception.class)
public class RecordRepository {
public RecordRepository() {}
public void insert(Record record) throws Exception {
JDBCConfig jdbcConfig = new JDBCConfig();
SimpleJdbcInsert messageInsert = new SimpleJdbcInsert(jdbcConfig.postgresDataSource());
messageInsert.withTableName(record.tableName()).execute(record.content());
throw new Exception();
}
}
然后我写了一个调用insert方法的客户端类
@EnableJdbcRepositories()
@Configuration
public class RecordClient {
@Autowired
private RecordRepository repository;
public void insert(Record r) throws Exception {
repository.insert(r);
}
}
我希望在调用RecordClient
'方法时不会向 db 插入任何记录,因为' throws 。而是添加了记录。insert()
RecordRespository
insert()
Exception
我错过了什么?
编辑。这是我配置数据源的类
@Configuration
@EnableTransactionManagement
public class JDBCConfig {
@Bean
public DataSource postgresDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/db");
dataSource.setUsername("postgres");
dataSource.setPassword("root");
return dataSource;
}
}
解决方案
您必须注入datasource
而不是手动创建它。我猜是因为@Transactional
仅适用于 Spring 托管 bean。如果您通过调用new
构造函数(如 this new JDBCConfig(). postgresDataSource()
)创建数据源实例,则您正在手动创建它,它不是 Spring 托管的 bean。
@Repository
@Transactional(rollbackFor = Exception.class)
public class RecordRepository {
@Autowired
DataSource dataSource;
public RecordRepository() {}
public void insert(Record record) throws Exception {
SimpleJdbcInsert messageInsert = new SimpleJdbcInsert(dataSource);
messageInsert.withTableName(record.tableName()).execute(record.contents());
throw new Exception();
}
}
推荐阅读
- c++ - 如何对指针数据成员强制执行 const 正确性
- javascript - 如何处理 onClick 而不是 href
- python - 如何使用 Pandas concat 导入多个 csv、分配变量并连接到一个 DataFrame 中?
- flutter - 在颤动的同一页面上有2个具有相同手势的手势检测器
- flutter - 展开 Flutter 中的应用栏以允许多行标题?
- arrays - Mongoose 填充虚拟返回数组内的数组
- javascript - 访问导航方法 React-Big-Calendar 和 Typescript
- python - 如何使用相同的测试数据测试 .tflite 模型以证明其行为与原始模型相同?
- python - 在 pandas 列/索引上应用 NLTK 词干提取
- r - 不能做假期矢量图