4
我使用的是Spring的NamedParameterJdbcTemplate
,我試圖使用@Transactional
來確保兩個插入既可以持久保存到數據庫,也可以回滾到一個,以防另一個插入失敗。Spring @Transactional不回滾
的代碼被設計成與MySQL運行並且正在與H2在存儲器測試。
它不工作......第二次插入失敗,但第一次沒有回滾。
下面是相關的類:
MySpringConfig.java
package com.MyPackage.spring
@Configuration
@ComponentScan({ "com.MyPackage" })
public class MySpringConfig {
@Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate() throws Exception {
return new NamedParameterJdbcTemplate(dataSource());
}
@Bean
public DataSourceTransactionManager dataSourceTransactionManager() throws Exception {
return new DataSourceTransactionManager(dataSource());
}
@Bean(name = "customerEntitiesDataSource")
public DataSource dataSource() throws Exception {
Properties properties = new Properties();
properties.put("url", "db-url");
properties.put("username", "uName");
properties.put("password", "pwd");
BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
return dataSource;
}
}
MyDao.java
package com.MyPackage.dao
@Repository
public class MyDao {
private ObjectMapper mapper = new ObjectMapper();
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
private static String INSERT_ELEMENT_QUERY = "INSERT INTO TableA..." + " VALUES (:param1, :param2)";
@Transactional(rollbackFor = {Exception.class}, propagation=Propagation.REQUIRED)
public void storeElements(List<Element> element) {
Stream<HashMap<String, Object>> hashMapStream = elements.stream().map(
element -> {
HashMap<String, Object> params = new HashMap<>();
params.put("param1", element.getParam1());
params.put("param2", element.getParam2());
return params;
}
);
List<Map<String, Object>> collect = hashMapStream.collect(Collectors.<Map<String, Object>>toList());
Map<String, Object>[] batchValues = new Map[]{};
batchValues = collect.toArray(batchValues);
jdbcTemplate.batchUpdate(INSERT_ELEMENT_QUERY, batchValues);
computers.stream().forEach(element -> saveExtraData(element));
}
private static String INSERT_ELEMENT_EXTRA_DATA_QUERY = "INSERT INTO TableB... Values (:val1, :val2)";
@Transactional(rollbackFor = {Exception.class}, propagation=Propagation.REQUIRED)
public void saveExtraData(Element element) {
Stream<HashMap<String, Object>> hashMapStream = element.getExtraData().stream().map(
extra -> {
HashMap<String, Object> params = new HashMap<>();
params.put("val1", extra.getVal1());
params.put("val2", extra.getVal2());
return params;
}
);
List<Map<String, Object>> collect = hashMapStream.collect(Collectors.<Map<String, Object>>toList());
Map<String, Object>[] batchValues = new Map[]{};
batchValues = collect.toArray(batchValues);
jdbcTemplate.batchUpdate(INSERT_ELEMENT_EXTRA_DATA_QUERY , batchValues);
}
}
我跑的測試:發送列表元素到storeElements()
但確保其中一個元素有extraData
太長,無法存儲在TableB
中。然後我檢查數據庫以確保沒有元素存儲在數據庫中。
插入失敗,但沒有回滾。
整個代碼是一個彈簧組,從試驗,一路通過對storeElements
方法。
運行調試,我看到沒有一個DataSourceTransactionManager對象方法被調用,除了構造函數,在加載Spring上下文時,它的創作。
我在這裏錯過了什麼?