2

In Springboot every service that I call it opens a transaction and when the service return it closes that connection but in my case I need to create one method that will run synchronized (this method will only run inside a non synchronized method) and he need to OPEN AND CLOSE a transaction independents if there's are one opened or not, and every SQL action inside that method only will rollback if THAT method throws an error. if the method that called it throws an error he won't rollback anything that the synchronized method did.

So I try to use this sample:

@Service
public class MyService {
    @Autowired
    private MyRepository myRepository;

    public void methodNotSyncronized(String arg1, String arg2){
        logger.debug("init method no syncronied");
        MyObjct myObj = myRepository.findOne(1);

        methodSyncronized(arg2);

        myRepository.save(myObj);   //If I got some error here everything that methodSyncronized did should remaining
        logger.debug("finish method no syncronied");
    }

    @Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
    private synchronized  String methodSyncronized(String arg){
        logger.debug("init method  syncronied");
        //Here I will insert or delete something    
    }

}

But when I debug this code I got:

o.h.e.t.internal.TransactionImpl         : begin
                       myService         : init method no syncronied
                       myService         : init method  syncronied
                       myService         : finish method no syncronied                     
o.h.e.t.internal.TransactionImpl         : committing

How can I fix this

And another thing, every service I call even if I only sum a number the hibernate print:

o.h.e.t.internal.TransactionImpl         : begin                       
o.h.e.t.internal.TransactionImpl         : committing

Even if I put the @Transactional(readOnly=true) in method

senjin.hajrulahovic
  • 2,961
  • 2
  • 17
  • 32
Fabio Ebner
  • 2,613
  • 16
  • 50
  • 77
  • Your emphasis on `synchronized` initially confused me as to what you were trying to accomplish - but it seems like the root issue is that `Propagation.REQUIRES_NEW` is not creating/committing its own transaction, and is rather reusing the existing transaction? How is transaction management configured in your application? – Craig Otis Oct 11 '18 at 16:21

1 Answers1

5

It is not working because Spring @Transaction method call by the method within the same class, does not work: It's a limitation of Spring AOP (dynamic objects and cglib).

Check this: Spring @Transaction method

Matej Marconak
  • 1,365
  • 3
  • 20
  • 25