Course contentsShow
← Software Engineering
Lesson 938 of 1,93329. Object-Relational MappingFree lesson

Unit of Work Pattern

Tracking changes to multiple objects and coordinating their persistence in a single transaction.

Unit of Work Pattern

What you'll learn: How to track changes across multiple objects and save them all together in a single, coordinated transaction.

The Core Problem

When building applications with databases, you often modify multiple related objects in memory during a single business operation—updating a customer's address, adding line items to an order, and recalculating totals. If you saved each object individually as you changed it, you'd have several problems: poor performance from multiple database round-trips, and partial failures leaving your database in an inconsistent state.

What the Unit of Work Does

The Unit of Work pattern acts like a transaction coordinator that sits between your business logic and the database. It keeps track of everything you've changed during a business operation—new objects to insert, modified objects to update, and deleted objects to remove. When you're ready, you call a single "commit" method, and it bundles all those changes into one database transaction.

Think of it like a shopping cart: you browse a store, adding and removing items. The cart remembers everything. Only when you check out does the actual payment transaction happen—all at once, atomically.

How It Works

The Unit of Work maintains internal lists:

  • New objects to INSERT
  • Modified objects to UPDATE
  • Deleted objects to DELETE

When you call commit(), it opens a transaction, executes all the SQL in the correct order (often respecting foreign key dependencies), and either commits everything or rolls back everything if any operation fails.

This pairs naturally with the Repository Pattern (which handles querying) and Data Mapper Pattern (which handles object-to-row mapping). The Repository registers changes with the Unit of Work; the Unit of Work uses Data Mappers to generate SQL.

Key Takeaway: The Unit of Work pattern tracks all changes to domain objects in memory and persists them in a single, atomic database transaction, ensuring consistency and improving performance.