hawarden_
hawarden_

Reputation: 2170

Spring transaction when calling private method

I have two questions.

If I have a method:

@Transactional
public method1(){
    method2()
}

public method2(){
    dao.save()
}

If there is an exception in method2(), will there be a rollback?

Another question:
If I have a method:

@Transactional
public method1(){
    method2()
}

private void method2(){
    dao.save()
}

If there is an exception in method2(), will there be a rollback?

Upvotes: 11

Views: 7734

Answers (2)

isah
isah

Reputation: 5351

Yes, there will be a rollback. The private methods will run within the same transaction. You should be aware that you can't have a @Transactional private method. It will not work without raising any error. This behavior is explained in Spring Docs:

Due to the proxy-based nature of Spring’s AOP framework, calls within the target object are by definition not intercepted. For JDK proxies, only public interface method calls on the proxy can be intercepted.

Upvotes: 8

Hugo G
Hugo G

Reputation: 16536

Yes to both. Transactional method means there must be no error during the entire runtime of the method.

If there is an error on one of the methods you are calling from within, these errors will be propagated and make the transaction fail and rollback.

Upvotes: 4

Related Questions