Reputation: 123
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?
Upvotes: 2
Views: 6986
Reputation: 18113
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(...);
}
});
}
}
Upvotes: 4
Reputation: 2890
If you want to execute multiple statements and want to be sure all or none executed, you can use transactions.
With spring you can use @Transactional annotation
@Transactional
public void transaction() { // Spring will begin transaction
doTransactionalStatements(); // Spring will rollback in case of RuntimeException
} // Spring will commit transaction
Upvotes: 3