Commit on jdbcTemplate or DataSource

Akhil picture Akhil · Aug 13, 2015 · Viewed 47.3k times · Source

I wanted to do commit and rollback using jdbcTemplate.

My question is based on this thread

How do I commit or rollback, should I do it on jdbcTemplate like

jdbcTemplate.commit();
jdbcTemplate.rollback();

Or there are some other ways to achieve commit and rollback functionality using jdbcTemplate.

Answer

dimitrisli picture dimitrisli · Aug 13, 2015

To call commit or rollback at will set the transactional boundaries programmatically and not declaratively.

For that reason you have to get hold of the PlatformTransactionManager - inject it that is in your DAO and perform the commit/ rollback operation yourself.

Sample code:

@Autowired private JdbcTemplate jdbcTemplate;
@Autowired private PlatformTransactionManager platformTransactionManager;

 //..

public void daoMethod(params) {
  DefaultTransactionDefinition paramTransactionDefinition = new    DefaultTransactionDefinition();

  TransactionStatus status=platformTransactionManager.getTransaction(paramTransactionDefinition );
try{
  String sqlQuery = "query";
  jdbcTemplate.update(sqlQuery, params);
  platformTransactionManager.commit(status);
}catch (Exception e) {
  platformTransactionManager.rollback(status);
}

Another approach is to get hold of the TransactionTemplate

Sample code:

@Autowired private JdbcTemplate jdbcTemplate;
@Autowired private TransactionTemplate transactionTemplate;

//..


//for operations where query does not return like delete
public void daoMethod(params) {
  transactionTemplate.execute(new TransactionCallbackWithoutResult() {
    protected void doInTransactionWithoutResult(TransactionStatus paramTransactionStatus) {
    try{
      String sqlQuery = "query";
      jdbcTemplate.update(query, params);
    }catch (Exception e) {
      paramTransactionStatus.setRollbackOnly();
    }
    }
  });
}

//for operations where query does return like insert
public int daoMethod(params) {
return  transactionTemplate.execute(new TransactionCallback<Integer>() {
  public Integer doInTransaction(TransactionStatus paramTransactionStatus) {
    String sqlQuery = "query";
    Object[] params = params;
    int[] types = myTypes;
    return jdbcTemplate.update(sqlQuery,params,types);
   }
 });
}}