Wednesday, 21 August 2013

Unit of Work Design Pattern - Implementation

Master Enterprise Architecture & Java!

Subscribe to Ram N Java for clean, beginner-friendly software architecture tutorials.

👉 Subscribe Now on YouTube

Implementing the Unit of Work Design Pattern

The Unit of Work Design Pattern maintains a list of objects affected by a business transaction and coordinates writing out changes and resolving concurrency problems. Rather than executing database queries for every single change, it bundles all modifications together into a single atomic operation.

1. Two Implementation Strategies for Tracking Changes

When registering changes with the Unit of Work, there are two primary approaches:

  • 1. Caller Registers the Changed Object: The client creates the Unit of Work instance, modifies values in the domain object (e.g., Customer), and explicitly calls the Unit of Work to register the changed object. Once all changes are completed, the client calls commit().
  • 2. Receiver Registers Itself: The client modifies the domain object, and the domain object itself automatically registers its state changes with the active Unit of Work instance. The client then issues the final commit() call.

2. Core Class Structure & Tracking Lists

A standard UnitOfWork class maintains internal collections to track entity states across the active business transaction:

  • newObjects: Tracks freshly created entities requiring database inserts.
  • dirtyObjects: Tracks existing entities whose fields have been modified.
  • removedObjects: Tracks entities marked for deletion from persistent storage.

3. Essential Registration Methods

  • registerNew(object): Validates that the entity is not already registered and places it into the newObjects list.
  • registerDirty(object): Confirms the entity has changed and appends it to the dirtyObjects list.
  • registerRemoved(object): Marks the entity for deletion by placing it in the removedObjects collection.
  • commit(): Iterates through the tracked collections in order—executing insertNew(), updateDirty(), and deleteRemoved()—flushing all persistent changes to the database in a single round-trip batch.

Recommended Related Videos from Ram N Java

Explore related object-relational and enterprise patterns with these tutorials:


Click here to watch in Youtube : https://www.youtube.com/watch?v=811tnO-pCaY

Click the below Image to Enlarge
Unit of Work Design Pattern - Implementation






Unit of Work Design Pattern - Implementation























See also:

  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials