Multiple commands in single UnitOfWork

Hi all.

We are having a problem when we are wrapping multiple commands in a single unit of work:

UnitOfWorkFactory in the code below is set up with SpringTransactionManager, and is the same instance bound to the SimpleCommandBus and the EventBus.

`
UnitOfWork unitOfWork = unitOfWorkFactory.createUnitOfWork();
try{
doPart1();// <- part1 produces 1 command, 3 events on aggregate 1
doPart2();// <- part2 produces 1 command, 2 events on aggregate 2
doPart3();// <- part3 produces 1 command, 2 events on aggregate 1
unitOfWork.commit();
} catch (RuntimeException rte) {
unitOfWork.rollback();
}

`

I realize this might not be an optimal solution, but we are dealing with a lot of legacy in our system that force us to try to wrap things together.

Our problem is that when part1 is executing, SimpleCommandBus#doDispatch starts a new UnitOfWork (using unitOfWorkFactory) and commits this uow. We observe that as part of this commit, events 1-2-3 are saved to the database. EventListeners are not affected at this point (Listeners are notified at our unitOfWork.commit()).
When part2 fails with a RuntimeException, the events from part1 are still in the database, and are not rolled back as part of our unitOfWork.rollback.

Are we doing something wrong here? Is there some way to defer writing events to the database for this scenario?

Please let me know if more details are needed :slight_smile:

Thank you,
Trond Marius

Hi,

are you sure there is a transaction runnning when doPart1() is executed. The SpringTransactionManager will only commit a transaction when the transaction it recieved is “new”. That’s only the case in outer transactions.
So even though the events are written to the database in doPart1() (since that UnitOfWork is committed), the outer transaction should still be able to roll it back.

Which database do you use? If MySQL, which DBEngine?
Which version of Axon?

Cheers,

Allard