Skip to main content

Unit Of Work

ArchitecturalData accessPerformanceAbout 2 min


When a business transaction is completed, all the updates are sent as one big unit of work to be
persisted in one go to minimize database round-trips.


Real-world example

Arms dealer has a database containing weapon information. Merchants all over the town are
constantly updating this information and it causes a high load on the database server. To make the
load more manageable we apply to Unit of Work pattern to send many small updates in batches.

In plain words

Unit of Work merges many small database updates in a single batch to optimize the number of

MartinFowler.comopen in new window says

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

Programmatic Example

Here's the Weapon entity that is being persisted in the database.

public class Weapon {
    private final Integer id;
    private final String name;

The essence of the implementation is the ArmsDealer implementing the Unit of Work pattern.
It maintains a map of database operations (context) that need to be done and when commit is
called it applies them in a single batch.

public interface IUnitOfWork<T> {
  String INSERT = "INSERT";
  String DELETE = "DELETE";
  String MODIFY = "MODIFY";

  void registerNew(T entity);

  void registerModified(T entity);

  void registerDeleted(T entity);

  void commit();

public class ArmsDealer implements IUnitOfWork<Weapon> {

    private final Map<String, List<Weapon>> context;
    private final WeaponDatabase weaponDatabase;

    public void registerNew(Weapon weapon) {"Registering {} for insert in context.", weapon.getName());
        register(weapon, UnitActions.INSERT.getActionValue());

    public void registerModified(Weapon weapon) {"Registering {} for modify in context.", weapon.getName());
        register(weapon, UnitActions.MODIFY.getActionValue());


    public void registerDeleted(Weapon weapon) {"Registering {} for delete in context.", weapon.getName());
        register(weapon, UnitActions.DELETE.getActionValue());

    private void register(Weapon weapon, String operation) {
        var weaponsToOperate = context.get(operation);
        if (weaponsToOperate == null) {
            weaponsToOperate = new ArrayList<>();
        context.put(operation, weaponsToOperate);

     * All UnitOfWork operations are batched and executed together on commit only.
    public void commit() {
        if (context == null || context.size() == 0) {
        }"Commit started");
        if (context.containsKey(UnitActions.INSERT.getActionValue())) {

        if (context.containsKey(UnitActions.MODIFY.getActionValue())) {
        if (context.containsKey(UnitActions.DELETE.getActionValue())) {
        }"Commit finished.");

    private void commitInsert() {
        var weaponsToBeInserted = context.get(UnitActions.INSERT.getActionValue());
        for (var weapon : weaponsToBeInserted) {
  "Inserting a new weapon {} to sales rack.", weapon.getName());

    private void commitModify() {
        var modifiedWeapons = context.get(UnitActions.MODIFY.getActionValue());
        for (var weapon : modifiedWeapons) {
  "Scheduling {} for modification work.", weapon.getName());

    private void commitDelete() {
        var deletedWeapons = context.get(UnitActions.DELETE.getActionValue());
        for (var weapon : deletedWeapons) {
  "Scrapping {}.", weapon.getName());

Here is how the whole app is put together.

// create some weapons
var enchantedHammer = new Weapon(1, "enchanted hammer");
var brokenGreatSword = new Weapon(2, "broken great sword");
var silverTrident = new Weapon(3, "silver trident");

// create repository
var weaponRepository = new ArmsDealer(new HashMap<String, List<Weapon>>(), new WeaponDatabase());

// perform operations on the weapons

Here is the console output.

21:39:21.984 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering enchanted hammer for insert in context.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering silver trident for modify in context.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering broken great sword for delete in context.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit started
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Inserting a new weapon enchanted hammer to sales rack.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Scheduling silver trident for modification work.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Scrapping broken great sword.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit finished.

Class diagram

alt text


Use the Unit Of Work pattern when

  • To optimize the time taken for database transactions.
  • To send changes to database as a unit of work which ensures atomicity of the transaction.
  • To reduce the number of database calls.