Reputation: 11
I have two datasource and i am using jdbctemplate batch update to update data in a batch but i am having one issue that whenever i am getting error in one of datasource in batch update than how we can rollback that inserted data from other datasource?
Service.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();
}
});
}
AddressRepository.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();
}
});
}
I am expecting to sync data into both the table of customer and address.
Upvotes: 0
Views: 90