2 Replies Latest reply on Jun 24, 2008 5:36 PM by jacob.orshalick

    how to rollback transactions without throwing exception on container?

      Hi,


      I have a batch process that stores records in a database and it must be atomic, but I don't want to throw an exception, instead I just want to put a message on the screen.


      I've got the current code but it doesn't rollback the previous inserts. How can I make the transaction automic?


      |
      try {
        for (int index=0; index < maxRecords; index++) {
          Record = new Record();
          // set data for next record
          // ...
          if (failValidation(record)) throw Exception("Invalid record");
          entityManager,persist(record);
        }
      }
      catch (Exception ex)
        facesMessages.add("The upload did not succeed. No records stored");
        Transaction.instance().setRollbackOnly();
      }|





      Now what happens is all the records upto the failed validation record still get inserted in the db even though I mark the transaction for rollback?


      How do you get batch uploads to be automic?


      Thanks


      Troy


        • 1. Re: how to rollback transactions without throwing exception on container?
          joaobmonteiro

          Hi,


          Wich database are you using? Check if autocommit is enabled. It could cause problems like this.


          Try to use an UserTransaction with begin/comitOrRollback.


          Regards,

          • 2. Re: how to rollback transactions without throwing exception on container?

            Why not just use MANUAL flush mode and only flush once the batch upload completes?  In this way you don't have to worry about rolling back the transaction, instead simply avoid flushing the persistence context should an error occur.  This just requires setting a message and returning null so the user is returned to the same view.


            Note that this means all but the failed upload will be associated with the persistence context in the conversation meaning that a subsequent flush would persist those entities (this is nice for an accept/reject scenario).  You can always clear the persistence context if this is not desirable.


            Hope it helps.