我有两个数据源,我正在使用 jdbctemplate 批量更新来批量更新数据,但我有一个问题,每当我在批量更新中的一个数据源中遇到错误时,我们如何回滚从其他数据源插入的数据?
服务.java
@Transactional(propagation = Propagation.REQUIRED)`
public void saveDataInBatch() {`
List<List<Customer>> mainCustomerList = getMainCustomerList();`
List<List<Address>> mainAddressList = getMainAddressList();`
for (int index = 0; index < 3; index++) {
saveData(mainCustomerList,mainAddressList,index);
}
}
@Transactional(propagation = Propagation.REQUIRED)
private void saveData(List<List<Customer>> mainCustomerList, List<List<Address>> mainAddressList, int index) {
customerRepository.saveSuccessBatch(mainCustomerList.get(index));
addressRepository.saveSuccessBatch(mainAddressList.get(index));
}`
CustomerRepository.java
@Transactional(propagation = Propagation.REQUIRES_NEW)
public int[] saveSuccessBatch(List<Customer> customerList) {
return jdbcTemplate.batchUpdate("insert into customer (age,first_name, last_name) values(?,?,?)",
new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Customer customer = customerList.get(i);
ps.setInt(1, customer.getAge());
ps.setString(2, customer.getFirstName());
ps.setString(3, customer.getLastName());
}
@Override
public int getBatchSize() {
return customerList.size();
}
});
}
地址库.java
@Transactional(propagation = Propagation.REQUIRES_NEW)
public int[] saveSuccessBatch(List<Address> addressList) {
return jdbcTemplate.batchUpdate("insert into address (city,street, zipCode) values(?,?,?)",
new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Address address = addressList.get(i);
ps.setString(1, address.getCity());
ps.setString(2, address.getStreet());
ps.setInt(3, address.getZipCode());
}
@Override
public int getBatchSize() {
return addressList.size();
}
});
}
我期望将数据同步到客户和地址表中。