The Unit Of Work pattern is a common pattern in enterprise application architectures.

It implements the concept of an "application transaction" that keeps track of:

dirty objects

new objects

removed objects

It records the state of the objects as it is before the transaction is started and will then rollback the state in memory upon rollback of the transaction. It allows adding additional behavior at commit, rollback etc., for example store all new, update all dirty and remove all removed objects in a persistent storage.

"Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."

This implementation implements the following transaction semantics:

TX REQUIRES

TX MANDATORY

TX NEVER

h2: UnitOfWorkListener

The user can implement listeners that allows him to trigger additional behaviour on specific events, such as begin, commit, rollback, dispose etc.

All listeners must implement that org.codehaus.aware.unitofwork.UnitOfWorkListener interface.

The Unit Of Work will not commit until all listeners have agreed on that. If for example on listener have set the transaction to rollBackOnly then the whole Unit Of Work transaction will rollback.

We also provide a convenience abstract adapter class that you can use if you are only interested in implementing a couple of methods and don't want to have empty method definitions. Just extend the org.codehaus.aware.unitofwork.UnitOfWorkAdapter class.

h2: Definition

The listeners are added to the Unit Of Work in the initialize method:

But in practice it is usually best to define this information outside the code, in a configuration file. Such as in the HibernateUnitOfWorkListener implementation, which uses the SpringContainer to configure the UnitOfWork.