[英]Is it possible to invoke transactional method from non transactional method in Spring?
Suppose I have a Repository class. 假设我有一个Repository类。
@Repository
class MyRepository {
@Transactional
void method1 () {
// some logic here
}
void method2 () {
// some logic here
method1();
// some logic here
}
}
Is it possible to do that in String? 可以在String中做到吗? And how this works?
以及它如何工作?
This does not work, since this a self call . 这是行不通的,因为这是一个自我呼唤 。 See
看到
Spring @Transaction method call by the method within the same class, does not work? Spring @Transaction方法由同一类中的方法调用,不起作用吗?
Depending on your application and its responsibilities, you could create another bean for method2()
. 根据您的应用程序及其职责,您可以为
method2()
创建另一个bean。 Apart from that, DAO methods should usually not be annotated @Transactional
. 除此之外,DAO方法通常不应使用
@Transactional
进行注释。 See 看到
Where does the @Transactional annotation belong? @Transactional注释在哪里?
This will not work because the method will go out of the scope of @Transaction
when you will call the method2
. 这将不起作用,因为当您调用
method2
时,该方法将超出@Transaction
的范围。 But you can apply a hack and call method2
using this
from method1
in the following way. 但是,你可以申请一个黑客攻击,并调用
method2
使用this
从method1
以下面的方式。
this.method2();
You cannot do that because Spring wraps methods that will be called from another class (service). 您不能这样做,因为Spring包装了将从另一个类(服务)调用的方法。 If you call annotated methods from withing the same class , Spring will do nothing as it cannot wrap them.
如果您从同一个类中调用带注释的方法,Spring将无能为力,因为它无法包装它们。
You should use self injection to call a Transactional
method from a non Transactional
one as in Spring you can't simply call @Transactional
method from the same instance because of AOP-proxy thing 你应该用自己注射调用
Transactional
从非法Transactional
一个在春天,你不能简单地调用@Transactional
从AOP因为代理的事情同样的实例方法
@Repository
class MyRepository {
@Autowired
MyRepository selfTxMyRepository;
@Transactional
void method1 () {
// some logic here
}
void method2 () {
// some logic here
selfTxMyRepository.method1();
// some logic here
}
}
See some explanation here: https://vladmihalcea.com/the-open-session-in-view-anti-pattern/ 在此处查看一些说明: https : //vladmihalcea.com/the-open-session-in-view-anti-pattern/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.