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.
As i understand, the jdbcTemplate. update() method will automatically commit the transaction and close the connection.
The JdbcTemplate can be used within a DAO implementation via direct instantiation with a DataSource reference, or be configured in a Spring IOC container and given to DAOs as a bean reference.
It loops through the list of people and, for each person, inserts that person into the BOOKINGS table by using the JdbcTemplate . This method is tagged with @Transactional , meaning that any failure causes the entire operation to roll back to its previous state and to re-throw the original exception.
If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion.
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);
}
});
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With