Save a list of objects to db but if fails one record, continue with jpa spring boot

Viewed 981

I am trying to save a long list of objects in the database (MS SQL) with repository.save (entity) in a for loop, but I want that if an object fails when inserting, I know because it is missing a field or there is some violation of a key, continue the other objects but without creating a transaction for each object to insert. All in one transaction. I have seen many posts on stack how to use norollbackon, etc but I always get the error of "" org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only "

I want to continue the loop even when an object fails for whatever exception ... is it possible? I don't think there isn't a way ..

I don't want any general rollback if a single object fails, just a rollback of that object but in the same transaction

I leave code:

General method in controller has: @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Exception.class)

insert in the loop of objects

try {
                        
    productoService.saveProduct(prodTmp);
                        
}catch(Exception e) {
                        
}

Method productService.saveProduct:

    @Transactional
    public Producto saveProduct(Producto prod) {
    
        return productoRepository.save(prod); 
    }
0 Answers
Related