Delete Records from multiple tables in Spring Batch

Viewed 454

I have a SQL script which performs delete operation from multiple tables based on say employee ids:

DELETE FROM EMP_ADDRESS where EMP_ID in (EMP_IDS);
DELETE FROM EMP_DETAILS where EMP_ID in (EMP_IDS);
DELETE FROM EMPLOYEE where EMP_ID in (EMP_IDS);

Is there a way to call the sql script from Spring batch by passing the employee ids? I tried an alternate approach where in the writer i get the ids and delete from the tables as below:

public class DeleteEmployeeData implements ItemWriter<EmployeeData>{

@Autowired
private JdbcTemplate jdbcTemplate;
    
@Override
public void write(List<? extends EmployeeData> items) throws Exception {

for(EmployeeData item : items){
jdbcTemplate.update(SQLConstants.DELETE_EMP_ADDRESS,item.getEmployeeId());
jdbcTemplate.update(SQLConstants.DELETE_EMP_DETAILS,item.getEmployeeId());
jdbcTemplate.update(SQLConstants.DELETE_EMPLOYEES,item.getEmployeeId());
}
}
}
  

This works. But i wanted to know if there is a better approach than this?

1 Answers

Your current approach with a chunk oriented step looks good to me:

  • The reader reads IDs
  • A processor filters IDs
  • And a composite writer with two writers: one to write xml and another one to delete items
Related