Search code examples
javatransactionsexecutionrollback

Java Transaction: how to stop program after rollback?


I have the following code that carries out database operations within a transaction:

  try {
                //start transaction
                repository.startTransaction();

               //carry out deletion logic
                repository.deletedata()

                //commit all 3 transactions
                 repository.commitTransaction();

      }catch (Exception e) {    
                 repository.rollback();
            }

Currently if there is an error when running, the application still continues running. However, I would like the execution of the program to stop after the data has been rolled back.

How can I best do this?


Solution

  • Firstly, to terminate the execution you should use your own business-level exception.

    Secondly, statement repository.rollback(); may fail, too. Just an idea.

    My approach would be:

    class MyApp {
        public static final main(){
            new MyApp().run();
        }
    
        private void run(){
            MyRepositoryProcessor proc = new MyRepositoryProcessor();
    
            try {
                // Some loop here maybe...
                proc.deleteFromRepo();
            } catch (MyDatabaseCommunicationException ex) {
                System.exit(-1);
            }
        }
    }
    
    class MyRepositoryProcessor {
        public void deleteFromRepo() throws MyDatabaseCommunicationException {
            try {
                //start transaction
                repository.startTransaction();
    
                //carry out deletion logic
                repository.deletedata()
    
                //commit all 3 operations
                repository.commitTransaction();
    
            }catch (Exception e) {
                try {
                    repository.rollback();
                } catch (Exception ex){
                    // Database connection failed completely, could not even do a rollback.
                }
                throw new MyDatabaseCommunicationException("Deletion failed");
            }
        }
    }