0

I have 3 methods defined the following way. methodX and methodY are defined in different classes. methodY and methodZAsync are defined in same class.

@Transactional(propagation = Propagation.REQUIRED)
public void methodX(){
    .....
    methodY();
    methodZAsync(); //
}


@Transactional(propagation = Propagation.REQUIRED)
public void methodY(){
    .....
    someDatabaseOperations();
    .....
}


@Async
public void methodZAsync(){
    .....
    pollingBasedOnDataOperationsOfMethodY();
    .....
}

The problem here is, methodZAsync requires methodY()'s DB operations to be committed before it can start it's work. And this fails because methodZAsync runs in a different thread.

One option is to make methodY's transaction to use @Transactional(propagation = Propagation.REQUIRES_NEW). But since methodY is used in multiple places with a different use cases, I'm not allowed to do that.

I've checked this question but TransactionSynchronization is an interface and Im not sure what to do with rest of the un-implemented methods.

So I thought, instead of making changes in methodY(), If I can somehow make methodX() to tell methodY() to use a new transaction(naive way: close current running transaction), It'll fix the things for me.

Is this doable from methodX() without having to modify methodY()?

Arun Gowda
  • 2,721
  • 5
  • 29
  • 50

2 Answers2

1

You can create a new wrapper method around methodY() that creates a new transaction. Then you can call this new method from methodX() without impacting any other use cases.

@Transactional(propagation = Propagation.REQUIRED)
public void methodX(){
    .....
    methodYInNewTxn();
    methodZAsync(); //
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodYInNewTxn() {
    methodY();
}

@Transactional(propagation = Propagation.REQUIRED)
public void methodY(){
    .....
    someDatabaseOperations();
    .....
}
0

Refer spring boot, there is also

@Transactional(propagation = Propagation.REQUIRES_NEW)

method are there go through. Hope you will get your proper answer

Nitish Bhardwaj
  • 1,113
  • 12
  • 29