Skip to main content

JDBC transaction rollback

We are advised to rollback a JDBC transaction in the catch block that handles SQLException, just as shown in the code below. But what if a runtime exception is thrown while after midway in the transaction? Control will never go to the catch block and the transaction will never be rolled back.

 


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class UnderstandingJdbcTransactions {

  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    String jdbcurl = "jdbc:derby:testdb;create=true";
    try {
      Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
      conn = DriverManager.getConnection(jdbcurl);
      conn.setAutoCommit(false);
      stmt = conn.createStatement();
      int rowsPopulated1 = 
        stmt.executeUpdate("INSERT INTO PEOPLE VALUES
         (01, 'Raja', 'Chandrashekhar')");
      //WHAT IF THERE ARE MORE SQL UPDATES BEING EXECUTED 
      //HERE AND A RUNTIME EXCEPTION IS THROWN
      int rowsPopulated2 = 
        stmt.executeUpdate("INSERT INTO PEOPLE VALUES
         (02, 'Mike', 'Russell')");
      conn.commit();
      conn.setAutoCommit(true);
    catch(SQLException sqle) {
      System.out.println("Caught Exception: " 
        sqle.getMessage());
      try {
        conn.rollback();
        System.out.println("Transaction rolled back");
      catch (SQLException e) {
        System.out.println("Could not rollback 
          transaction: " + e.getMessage());
      }
    catch (ClassNotFoundException e) {
      System.out.println("Could not find the database 
        driver class");
    finally {
      if(conn != null) {
        try {
          conn.close();
        catch(SQLException sqle) {
          System.out.println("Could not close 
          connection: " + sqle.getMessage());
        }
      }
    }
  }
}
Java2html
 
There are two ways to handle this issue. The first is to explicitly set a flag in this class if the transaction commits. In the finally block we should check the flag. If it has not been set, it means that the transaction could not be commited and must be rolled back. Another way is to catch 'Exception' after 'SQLException'. If a runtime exception is thrown we will handle it in the catch block by rolling back the transaction and rethrowing the RuntimeException.
 
What do you think? Is this a workable solution? Which os the two approaches would you favor? 

Comments

Unknown said…
A third option would be to always do a rollback in the finally block - doing a rollback after doing commit doesn't change anything. I guess there is some sort of performance issue to consider but I doubt it's significant.
Parag said…
@Jens, That is also an option. I did not think of it when I wrote this post, but you are right... we can rollback in finally. It results in fewer lines of code, with a slight runtime impact.

--
Thanks
Parag

Popular posts from this blog

Testing Groovy domain classes

If you are trying to test Grails domain class constraints by putting your unit test cases in the 'test/unit' directory, then your tests will fail because the domain objects will not have the 'valdate' method. This can be resolved in two ways: Place the test cases inside test/integration (which will slow things down) Use the method 'mockForConstraintsTests(Trail)' to create mock method in your domain class and continue writing your test cases in 'test/unit' What follows is some example code around this finding. I am working on a Groovy on Grails project for a website to help programmers keep up and refresh their skills. I started with some domain classes and then moved on to write some unit tests. When we create a Grails project using grails create-app , it creates several directories, one of which is a directory called 'test' for holding unit tests. This directory contains two directories, 'unit', and 'integration' for unit and ...

Running your own one person company

Recently there was a post on PuneTech on mom's re-entering the IT work force after a break. Two of the biggest concerns mentioned were : Coping with vast advances (changes) in the IT landscape Balancing work and family responsibilities Since I have been running a one person company for a good amount of time, I suggested that as an option. In this post I will discuss various aspects of running a one person company. Advantages: You have full control of your time. You can choose to spend as much or as little time as you would like. There is also a good chance that you will be able to decide when you want to spend that time. You get to work on something that you enjoy doing. Tremendous work satisfaction. You have the option of working from home. Disadvantages: It can take a little while for the work to get set, so you may not be able to see revenues for some time. It takes a huge amount of discipline to work without a boss, and without deadlines. You will not get the benefits (insuranc...

My first impressions of Python for the second time

I had worked a bit in Python many years back. Since then I have forgotten almost everything I learned back then. I think the phrase "Out of sight out of mind" applies perfectly to my mind. Since the last few days, I have started relearning Python, and this time I am recording my impressions of Python after having come to it from a Java background. Indentation: Python uses indentation to specify blocks of code, instead of curly braces. I like this, because we anyways indent code to increase readability, so why not achieve two tasks together. Code looks much cleaner without the curly braces. However there may be a little downside. Everyone in the team will have to set up their IDE's in the same way. Things might fall apart if some people use tabs and others use spaces for indentation. Access modifiers: Python does not have public, private, and protected keywords. Everything is public. However, private members can be specified with a leading single underscore. If we use do...