Issue
I am learning JDBS template and wonder if there is a way to rollback operation.
It is easy to do it using JDBC, just
conn.setAutoCommit(false);
// DoinП stuff
con.rollback();
But is there a way do the same using JDBS template?
Solution
You should use the spring-boot-starter-data-jdbc like in this guide
Thanks to this spring-boot-starter-data-jdbc
and to the spring boot autoconfiguration mechanism, a jdbc template bean and a transaction manager bean will be created for you.
Then you can use @Transactional
annotation on non private method to wrap your code into a transaction :
@Transactional
public void methodA() {
jdbcTemplate.update(...);
jdbcTemplate.update(...);
}
or you can use a transacionTemplate to handle the transaction programatically
@Service
public class ServiceA {
private final TransactionTemplate transactionTemplate;
public SimpleService(PlatformTransactionManager transactionManager) {
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
public void methodA() {
transactionTemplate.execute(new TransactionCallback<>() {
public Object doInTransaction(TransactionStatus status) {
jdbcTemplate.update(...);
jdbcTemplate.update(...);
return jdbcTemplate.query(...);
}
});
}
}
Answered By - Olivier Boissé
Answer Checked By - Terry (JavaFixing Volunteer)