rmpt
rmpt

Reputation: 654

Spring PlatformTransactionManager - concurrent transactions

I'm implementing a JDBC database access API (basically a wrapper) and I'm usnig Spring JdbcTemplate with PlatformTransactionManager to handle transactional operations. Everything looks ok, but I cannot understand how jdbcTemplate manage concurrent transactions. I'll give you a simplified example based on the creation of students to make my point. Let's create 2 students, John and Jack. The first without erros and the seconds with one error, there's the steps and the code below.

StudentDAO

public class StudentJDBCTemplate implements StudentDAO {

   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   private PlatformTransactionManager transactionManager;

   // constructor, getters and setters

  public TransactionStatus startTransaction() throws TransactionException {
      TransactionDefinition def = new DefaultTransactionDefinition();
      transactionManager.getTransaction(def);
  }

  public void commitTransaction(TransactionStatus status) throws TransactionException {
      transactionManager.commit(status);
  }

  public void rollbackTransaction(TransactionStatus status) throws TransactionException {
      transactionManager.rollback(status);
  }

   public void create(String name, Integer age){
      String SQL1 = "insert into Student (name, age) values (?, ?)";
      jdbcTemplateObject.update( SQL1, name, age);
      return;
   }
}

MainApp

public class MainApp {
    public static void main(String[] args){
        // setup db connection etc

       StudentJDBCTemplate studentDao = new StudentJDBCTemplate();

       TransactionStatus txJohn = studentDao.startTransaction();
       TransactionStatus txJack = studentDao.startTransaction();

       studentDao.create("John", 20);

       try {
           studentDao.create("Jack", null); // **FORCE EXCEPTION**
       } catch(Exception e){
           studentDao.rollback(txJack);
       }
       studentDao.commit(txJohn);
    }
}

How JdbcTemplate knows that 1 transaction is ok but the other is not? From my undertanding, despite we have created 2 transactions, JdbcTemplate will rollback Jack AND John transactions, because query, execute and update methods does not require TransactionStatus as a parameter. That means that Spring jdbcTemplate only supports 1 transaction at time?!

Upvotes: 1

Views: 1322

Answers (1)

Har Krishan
Har Krishan

Reputation: 273

All the operations in a single transaction are always executed as a single unit so either all will be committed or none.

If John starts a transaction which insert and then update then either both (insert and update) will succeed or none and will not be impacted by the transaction started by Jack.

Now how the concurrent transactions interfere with each other is controlled by isolation level i.e. how a transaction sees data modified by another concurrent transaction.

Upvotes: 2

Related Questions