How to correctly use Transaction, when working with JdbcTempalte?

Viewed 48

I need to use JdbcTemplate in Spring.

For example, I have:

void someFunction() {
  // Some logic
  sql();

}

@Transactional
void sql() {
   jdbcTemplate.batchUpdate(...);
}

As I understand, this is not a valid usage of transactions.

So, can I use @Transactional annotation for JdbcTemplate as follows:

@Transactional
void someFunction() {
  // Some logic
  jdbcTemplate.batchUpdate(...);
}

or it's better to use TransactionTemplate?

1 Answers

Yes you can use the annotation like that, however review this part of the Spring documentation that states

'Due to the proxy-based nature of Spring's AOP framework, protected methods are by definition not intercepted, neither for JDK proxies (where this isn't applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only!'.

Therefore, your method should be a public method, which it currently is not. Update it, and your method should work.

Related