简体   繁体   中英

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) {
 ...
}

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.

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM