0

I have got a method where it will update two tables (table A and table B). I would want the whole transaction to be atomic so that if updating table A failed (either the database update failed, or the code thrown exception before making the actual database call), then it will not update table B so as to preserve data consistency. My questions:

  1. I think of using @Transactional annotation to do so, is this usage correct ?

  2. I have seen some placing the @Transactional at both the class level and also the method level, if I only put at the method level, will it still work ?

  3. Suppose for the following. If I only place @Transactional in the private method of updateValue, does it mean only the update action from tableADao.updateValue(value) and tableBDao.updateValue(value) (but not tableADao.get(userId)) will be wrapped inside one transaction ?

public void updateMethod(final Long userId, Integer value) {
  //some processing
  Integer value = tableADao.get(userId);
  //some processing

  updateValue(value);
  //some processing
}

@Transactional
private void updateValue(final Integer value) {
  tableADao.updateValue(value);
  tableBDao.updateValue(value);
}
once
  • 536
  • 7
  • 21

1 Answers1

0
  1. Yes, @Transactional is suited for this.
  2. Yes, @Transactional also works at method level, but with a catch that I will address in the following topic (this also applies to @Transactional at class level).
  3. Assuming your code, that would not work, the reason being the way Spring provides transactional functionality. It is based on Spring AOP and on a Proxy for your bean. Transactional functionality is handled by this Proxy, but the catch is that only the calls from another bean to your bean are going through this Proxy. This means that calls between methods in the same bean do not go through the Proxy and as a consequence transactional functionality is not provided. Having said that, unless you add @Transactional to your public updateMethod method and you call it from another bean, your code will not work as you expect.

Check the comments to your question, there are some useful links there.

João Dias
  • 16,277
  • 6
  • 33
  • 45