Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Begin and Rollback transactions with JdbcTemplate

i'm working with spring jdbcTemplate in some desktop aplications.

i'm trying to rollback some database operations, but i don't know how can i manage the transaction with this object(JdbcTemplate). I'm doing multiple inserts and updates through a methods sequence. When any operation fails i need rollback all previous operations.

any idea?


Updated... i tried to use @Transactional, but the rolling back doesn't happend.

Do i need some previous configuration on my JdbcTemplate?

My Example:

  @Transactional(rollingbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
  public void Testing(){
    jdbcTemplate.exec("Insert into table Acess_Level(IdLevel,Description) values(1,'Admin')");
    jdbcTemplate.exec("Insert into table Acess_Level(IdLevel,Description) values(STRING,'Admin')");
    }

The IdLevel is a NUMERIC parameter, so... in our second command will occur an exception. When i see the table in database, i can see the first insert... but, i think this operation should be roll back.

what is wrong?

like image 616
Cleiton Ribeiro Avatar asked Oct 22 '25 22:10

Cleiton Ribeiro


2 Answers

JdbcTemplate doesn't handle transaction by itself. You should use a TransactionTemplate, or @Transactional annotations : with this, you can then group operations within a transaction, and rollback all operations in case of errors.

@Transactional
public void someMethod() {
  jdbcTemplate.update(..)
}
like image 152
Jérémie B Avatar answered Oct 24 '25 13:10

Jérémie B


In Spring private methods don't get proxied, so the annotation will not work. See this question: Does Spring @Transactional attribute work on a private method?.

Create a service and put @Transactional on the public methods that you want to be transactional. It would be more normal-looking Spring code to have simple DAO objects that each do one job and have several of them injected than it would to have a complicated DAO object that performed multiple SQL calls within its own transaction.

like image 39
Nathan Hughes Avatar answered Oct 24 '25 14:10

Nathan Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!