Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Transactional propagation on private methods

I have the following code:

@Service
public class MyService implements IMyService {
    @Inject
    IAnotherService anotherService;
    // injects go here
    // some code
    @Transactional(isolation=Isolation.SERIALIZABLE)
    public Result myMethod() {
        // stuff done here
        return this.myPrivateMethod()
    } 

    private Result myPrivateMethod() {
         // stuff done here
         // multiple DAO SAVE of anObject
         anotherService.processSomething(anObject);
         return result; 
    }
}

@Service
public class AnotherService implements IAnotherService {
      // injections here
      // other stuff

      @Transactional(isolation=SERIALIZABLE)
      public Result processSomething(Object anObject) {
         // some code here
         // multiple dao save
         // manipulation of anObject
         dao.save(anObject);
      }
}
  1. Does the @Transactional behavior propagate to myPrivateMethod even if it's private?.
  2. If a Runtime Exception occurs on processSomething(), and processSomething is called from myPrivateMethod, will myPrivateMethod and myMethod do rollback?.
  3. If the answer to 1 and 2 is no, how can I achieve that without having to create another @Service?. How can I do extract method and invoke multiple private methods inside a public service method within a @Transactional context?.
  4. Is isolation=Isolation.SERIALIZABLE option a good alternative to synchronized methods?.

I know this has been answered already but I'm still having doubts.

like image 645
dantebarba Avatar asked Sep 22 '15 13:09

dantebarba


1 Answers

  1. If myPrivateMethod is called from public method that is annotated @Transactional it is propagated.
  2. If first condition is TRUE yes it will roll-back.
  3. It is misconception to compare isolation level on database and synchronization of class method. They shouldn't be compared at all. If your method will be used in multi-thread env you should synchronize method(be aware in some circumstances it is not enough to have thread safe code). Isolation level SERIALIZABLE is used on database level. It is most restrictive isolation level, and it can lock a lot of tables when you run some query, before it is is done, to help your data not turn to some inconsistent state. You should be sure that you need this level of isolation because this can lead to performance issues. So answer is NO.
like image 86
mommcilo Avatar answered Sep 29 '22 16:09

mommcilo