如何在使用JdbcTemplate时正确使用事务?

huangapple go评论73阅读模式
英文:

How to correctly use Transaction, when working with JdbcTempalte?

问题

我需要在Spring中使用JdbcTemplate

例如,我有:

void someFunction() {
  // 一些逻辑
  sql();
}

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

据我理解,这不是有效的事务使用方式。

那么,我能否像下面这样为JdbcTemplate使用@Transactional注解:

@Transactional
void someFunction() {
  // 一些逻辑
  jdbcTemplate.batchUpdate(...);
}

还是最好使用TransactionTemplate

英文:

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

得分: 0

是的,您可以像那样使用注解,但是请查阅Spring文档中关于这部分的说明:

“由于Spring AOP框架的基于代理的特性,受保护的方法从定义上来说不会被拦截,无论是对于JDK代理(在这种情况下不适用)还是CGLIB代理(在技术上虽然可行,但不建议用于AOP目的)。因此,任何给定的切入点只会匹配公共方法!”

因此,您的方法应该是一个公共方法,而目前它不是。请将其更新为公共方法,然后您的方法应该可以正常工作。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月31日 16:03:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63667009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定