Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 443
hawarden_ Avatar asked Aug 11 '17 08:08

hawarden_


People also ask

Does @transactional work on private methods?

The answer your question is no - @Transactional will have no effect if used to annotate private methods. The proxy generator will ignore them. When using proxies, you should apply the @Transactional annotation only to methods with public visibility.

What does @transactional do in Spring?

At a high level, when a class declares @Transactional on itself or its members, Spring creates a proxy that implements the same interface(s) as the class you're annotating. In other words, Spring wraps the bean in the proxy and the bean itself has no knowledge of it.

Does Spring @transactional lock table?

"@Transactional" as itself on any isolation level doesn't enabling any locking. To achieve locking behaviour you should use "@Lock" annotation or use " for update" in your query.


1 Answers

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.

like image 168
isah Avatar answered Oct 05 '22 02:10

isah