Close

Spring - Using TransactionTemplate

[Last Updated: Sep 5, 2017]

This example demonstrate how to use TransactionTemplate class which simplifies programmatic transaction execution by wrapping TransactionManager API.

Example

We are going to reuse our previous example, so there's only one class where we are doing transactions. Instead of using TransactionManager, we will use TransactionTemplate in this example.

@Component
public class OrderItemClientBean {

  @Autowired
  private PlatformTransactionManager transactionManager;
  @Autowired
  private Dao<OrderItem> dao;

  public void persistOrderItems() {
      TransactionTemplate template = new TransactionTemplate(transactionManager);

      template.execute(new TransactionCallbackWithoutResult() {
          @Override
          protected void doInTransactionWithoutResult(TransactionStatus status) {
              try {
                  long id = dao.save(new OrderItem("BWell Ethernet Cable", 5));
                  System.out.println("id generated: " + id);
                  id = dao.save(new OrderItem("EDrive SSD", 2000));
                  System.out.println("id generated: " + id);
              } catch (Exception e) {
                  logException(e);
              }
          }
      });
      System.out.println("loaded items: " + dao.loadAll());
      System.out.println("-- second attempt --");

      //new transaction boundary
      template.execute(new TransactionCallbackWithoutResult() {
          @Override
          protected void doInTransactionWithoutResult(TransactionStatus status) {
              try {
                  long id = dao.save(new OrderItem("BWell Ethernet Cable", 5));
                  System.out.println("id generated: " + id);
                  id = dao.save(new OrderItem("EDrive SSD", 20));
                  System.out.println("id generated: " + id);
              } catch (Exception e) {
                  logException(e);
              }
          }
      });
      System.out.println("loaded items: " + dao.loadAll());
  }

  private static void logException(Exception e) {
      System.out.println("-- exception message --");
      System.err.println(e.getMessage());
      System.out.println("---------");
  }
}

In above example, we are performing two transactions. The first transaction is inserting a value for OrderItem#qty which is out of the integer range defined in the corresponding table column, so that will end up in an exception and the transaction will be rolled back by TransactionTemplate. The second transaction should be committed successfully.

Main class

public class ExampleMain {
  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);
      OrderItemClientBean orderItemClientBean = context.getBean(OrderItemClientBean.class);
      orderItemClientBean.persistOrderItems();
  }
}

Output

id generated: 1
-- exception message --
PreparedStatementCallback; SQL []; Check constraint violation: "((QTY > 0)
AND (QTY <= 100))"; SQL statement:
insert into ORDER_ITEM (ITEM, QTY) values (?, ?) [23513-196]; nested exception is org.h2.jdbc.JdbcSQLException: Check constraint violation: "((QTY > 0)
AND (QTY <= 100))"; SQL statement:
insert into ORDER_ITEM (ITEM, QTY) values (?, ?) [23513-196]
---------
loaded items: [OrderItem{id=1, item='BWell Ethernet Cable', qty=5}]
-- second attempt --
id generated: 3
id generated: 4
loaded items: [OrderItem{id=1, item='BWell Ethernet Cable', qty=5}, OrderItem{id=3, item='BWell Ethernet Cable', qty=5}, OrderItem{id=4, item='EDrive SSD', qty=20}]

Returning a result from transaction

To return a result from TransactionTemplate, use TransactionCallback instance as the argument of execute() method as shown below:

 Integer result = transactionTemplate.execute(new TransactionCallback<Integer>() {
  public Integer doInTransaction(TransactionStatus paramTransactionStatus) {
    .......
    return anInteger;
   }
 });
}}

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.10.RELEASE: Spring Context.
  • spring-jdbc 4.3.10.RELEASE: Spring JDBC.
  • h2 1.4.196: H2 Database Engine.
  • JDK 1.8
  • Maven 3.3.9

TransactionTemplate Example Select All Download
  • transaction-template-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • OrderItemClientBean.java
          • resources

    See Also