How to roll back a spring jpa repo.save() function

Viewed 5281

I've seen several different posts regarding this topic, but most of them tend to be that it's not working. What I'm trying to do is save several objects in a loop, but if one of them fails -> rollback all of the saved objects.

Here is my current code.

@Override
public Fleet saveFleet(String fleetId, List<String> serialNoList) {

    fleet = new Fleet();
    Fleet tempFleet = new Fleet();
    fleet.setKey(new FleetKey());

    //Change this to string utils uppercase
    fleet.getKey().setFleetId(StringUtils.upperCase(fleetId));
    fleet.getKey().setUserId(StringUtils.upperCase(userService.getCurrentUser().getUserId()));
    fleet.getKey().setDealerCd("USER");

    for (int i = 0; i < serialNoList.size(); i++) {
        //Try catch block?

           tempFleet = fleetRepo.save(fleet);
       }
    //commit if all the data goes correctly, rollback if there is an exception. 
    return tempFleet;
}
3 Answers

Add @Transactional(rollbackFor = Exception.class) to the top of the method. Spring will rollback all data within this transaction for you if any exception is thrown by database.

You can use @Transactional annotation to rollback transaction in case of exception.

Related