英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论