I need to persist a list of objects in DB as a batched-insert, but don't want the entire batch to get rolled back if one/more of the objects fail; i.e. any records that were successfully saved should remain in DB.
Also, I need to identify IDs of objects that failed to be persisted, and return that list out to caller.
Following is a simple demo of what I need to do; shown are the Class of the object (a list of which I need to persist) and a fragment of the DAO method:
class Student {
int code;
String name;
...
}
public List<Integer> bulkAddStudents(List<Student> students) {
String query = "INSERT INTO STUDENT (CODE, NAME) VALUES (:code, :name)";
List<Integer> failedCodes = new LinkedList<Integer>(); // to store failed student-codes
List<Map<String, Object>> params = new ArrayList<>();
try {
students.forEach(student -> {
Map<String, Object> stu = new HashMap<>();
stu.put("code", student.getCode());
stu.put("name", student.getName());
params.add(stu);
});
namedJdbcTemplate.batchUpdate(query, params.toArray(new HashMap[0]));
// TODO prevent transactional rollback for failed records
// TODO get student numbers of failed records; add to "failedCodes"
} catch (Exception ex) {
throw new DAOException(ex);
}
return failedCodes; // return IDs of failed records
}
This might not fit a common usecase, but does anyone know how to do exactly the above? Thanks in advance.