Search code examples
spring-mvctransactionsjdbctemplate

Transaction RollBack in Spring MVC for List


I have list of Entity Object.I am calling save method of service class from controller. Service class is annotated with @Transactional annotation. Since the save method is doing some validations inside, So let's say if my 3rd Object of the list is having some validation issue, service class will throw an exception and that will be rolled back, but my previous 2 objects are already saved. I want to rollback completely if any of the list object is having an validation issue. Please Suggest, thanks in advance.I am using JDBCTemplate, no ORM.


Solution

  • Why not save all objects/entities in a single call intead of calling save for each object in separate transaction,

    @Transactional
    public List<Entity> saveAll(final List<Entity> entities) {
        return yourRepository.saveAll(entities);
    }
    

    This will ensure all entities saved automatically (all save or none) and will be returned all saved(managed) entities.