Question

I have a Grails Service with a method processing multiple files. Each file will be processed (inserting n-domains) and if correct it will be moved in a folder "backup", if something goes wrong (validations or domain saving) it will be moved in a folder "errors" I need to commit database changes on file correct and rollback if file is wrong (not loosing previous files processed on database)

now I have @Transactional on service class, but it commits or rollback all data

@Transactional
class DocumentoTrasportoService extends GenericService {

  public void processFiles(String path){
     def pathFile = new File(path)
     pathFile.eachFile{
        try {
            processFile(it)
            //I want to commit here
            //move file to folder "backup"
        } catch (Exception ex){
            //I want to rollback here
            //move file to folder "errors"
        }
     }
  }

  public void processFile(File file){
     //read file
     //do validations
     //insert domains
  }

}

Suggestions?

Was it helpful?

Solution

Since you need more programatic and fine grained control of your transactions within that service I would recommend you look at using withTransaction instead. This way you can execute each file within it's own transaction instead of a single transaction as a service method.

In theory your code would look something like this:

class DocumentoTrasportoService extends GenericService {

  public void processFiles(String path){
     def pathFile = new File(path)
     pathFile.eachFile{
        MyDomainClass.withTransaction { status ->
          try {
              processFile(it)
              //move file to folder "backup"
          } catch (Exception ex){
              //I want to rollback here
              status.setRollbackOnly()
              //move file to folder "errors"
          }
       } // end of transaction
     }
  }

  public void processFile(File file){
     //read file
     //do validations
     //insert domains
  }

Notice that you only need to set the status for rolling back the transaction. Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top