Spring boot batch insert, rollback as groups

Viewed 23

So i'm working on a spring boot project and i need to insert some bulk data. But i want to insert it as groups like say 20 entities per group and if something goes wrong i want it to rollback the group not the whole thing. How can i achive that?

Here is what i have in mind:

@Transactional
public void saveBatchAsGroups(List<EntityClass> data) {
    List<EntityClass> group = new ArrayList();
    for (EntityClass entity : data) {
        //some operations

        group.add(entity);
        if (group.size() > 19) {
            saveGroup(group);
            group.clear();
        }
    }
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveGroup(List<EntityClass> group) {
    someRepository.saveAll(group);
}

This way saveGroup opens a new transaction for every save operation.

Is this a good practice in terms of performance etc., can it done without a bunch of new transactions like with save points or something like that? what is the best way to achive this kind of job?

1 Answers

JPA doesn't now stacked transactions, so the outer @Transactional is at least confusing.

Other than that this looks ok. You might want to consider Spring Batch though, which is build for this kind of process.

Related