JohnWinter
JohnWinter

Reputation: 1023

Is it possible to invoke transactional method from non transactional method in Spring?

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 Spring? And how this works?

Upvotes: 11

Views: 17470

Answers (4)

Jad Chahine
Jad Chahine

Reputation: 7149

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/

Upvotes: 2

Farooq Khan
Farooq Khan

Reputation: 622

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();

Upvotes: 1

AntJavaDev
AntJavaDev

Reputation: 1262

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.

Upvotes: 1

user140547
user140547

Reputation: 8200

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?

Upvotes: 9

Related Questions