Erwin Engel
Erwin Engel

Reputation: 123

How does rollback() in JDBC Template work?

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

Answers (2)

Olivier Boissé
Olivier Boissé

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

Akif Hadziabdic
Akif Hadziabdic

Reputation: 2890

If you want to execute multiple statements and want to be sure all or none executed, you can use transactions.

  • First, you have to create a session and begin the transaction.
  • After, you can execute statements and commit the transaction.
  • But, in case of problems, you can rollback (undo previous statements).

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

Related Questions