[英]JDBC Spring data @Transactional not working
我正在使用 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
的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
構造函數(例如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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.