hudi
hudi

Reputation: 16555

How to use @Transactional in java

I have 2 public method (to make it easy to understand I simplify them) First method call second. My question is if I use @Transactional correctly. When I call this method from other class they should be in transaction

@Transactional
public int f1(Integer a) {
    return f2(a.toString());
}

@Transactional
public int f2(String b) {
 ...
}

Upvotes: 1

Views: 689

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136102

It should be kept in mind that calling a transactional method from the same bean will not work because it bypasses transactional proxy. In the above example, call from1 f1 to f2 actually ignores Transactional annotation on f2 method. It still works becuase f1 is transactional too.

Upvotes: 4

Krishan Babbar
Krishan Babbar

Reputation: 798

By using Transaction Propagation you can achieve what ever you want.

http://static.springsource.org/spring/docs/3.0.x/reference/transaction.html#tx-propagation

Upvotes: 0

In this example, you don't necessarily need the @Transactional around f1 unless you're doing something inside that method that needs to access persistent data. If you're using Spring's proxy AOP setup, then only method calls coming from another class will work, because the proxy AOP works by inserting a wrapper object around all of the class's methods. If you're using AspectJ, @Transactional advice will work properly even with private methods.

Upvotes: 1

Related Questions