Search code examples
javaspringhibernatetransactions

using spring transactionManager with Hibernate after transaction committed only one repository of two is actually being committed


I have a @Transactional method that changes the state of two entities of different, not related, repositories.

something like this:

@Transactional
public void foo() {
  A a = repoA.findById(1);
  a.setState(s1);
  B b = repoB.findById(1);
  b.setState(s2);
  // (and I also do repoA.save(a); and repoB.save(b); although it is redundant)
} 

I also have a transactional method bar that calls foo and publishes an event that is being caught by a TransactionalEventListener like this:

@Transactional 
public void bar() {
  foo();
  applicationEventPublisher.publishEvent(new AppEvent(123));
}

and

@Component
public class MyApplicationEventListener {

    @TransactionalEventListener
    public void handleAfterCommit(AppEvent appEvent){
       //do something;
    }
}

Now the issue is that in 80% of the time when handleAfterCommit method is invoked, only (A a ) is being committed but (B b) is losing its changes.

I need help to understand what is going on here, I tried to debug and explore the TransactionAspectSupport.currentTransactionStatus() but didn't find any insights.

Thanks,
Eilon


Solution

  • I found the issue, we are using a custom AttributeConverter and we didnt implement Equals for the relevant javav object, this caused every dirty check on select to fail and do a full update (overriding values that meanwhile have been changed)

    Thanks