Suppose I have a Repository class.
@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? 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?
Depending on your application and its responsibilities, you could create another bean for method2()
. Apart from that, DAO methods should usually not be annotated @Transactional
. See
Where does the @Transactional annotation belong?
This will not work because the method will go out of the scope of @Transaction
when you will call the method2
. But you can apply a hack and call method2
using this
from method1
in the following way.
this.method2();
You cannot do that because Spring wraps methods that will be called from another class (service). If you call annotated methods from withing the same class , Spring will do nothing as it cannot wrap them.
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
@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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.