@Transactional propagation on private methods
Asked Answered
P

1

9

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.

Pram answered 22/9, 2015 at 13:3 Comment(2)
What are the answers you found so far telling you? 1. yes 2. yes 3. not applicable, since 1 && 2 4. no, because it only works if the method is invoked within a transaction container.Cremate
#4396784 ---> Found some references that answer my questions partially but the main topic is not focused on the same case that I have. I really had to be sure if the transactional annotation is really working in my case. For question 4: And if I force Propagation.MANDATORY?Pram
E
10
  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.
Endure answered 22/9, 2015 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.