Unit of Work / Session pattern in ORMs
ORM session mechanics.
the Unit of Work tracks new, dirty, and deleted objects, then flushes them as one batched transaction at commit.
WHAT THIS TESTS Whether you understand how an ORM defers and batches persistence and why short-lived per-request sessions complicate concurrency.
WHY IT EXISTS Rather than writing to the database on every object mutation, the Unit of Work collects all changes made during a business operation and commits them together, minimizing round trips and keeping the database consistent within one transaction.
HOW IT WORKS The session tracks every object it loads or that you add. As you work, it classifies objects: new objects to insert, dirty objects whose tracked fields changed and need updates, and deleted objects to remove. Dirty detection works by comparing current field values against a snapshot taken at load, or via change notifications. On commit (or an explicit flush), the session translates this into ordered INSERT, UPDATE, and DELETE statements, ordering them to respect foreign-key constraints, and runs them inside a single database transaction so they all succeed or all roll back.
WHEN IT MATTERS / THE CHALLENGE In a stateless web application, each HTTP request typically opens a fresh session and closes it at the end. An entity loaded and shown to a user in one request is detached; by the time a later request submits an edit, another user may have changed that row. Without protection, the second write blindly overwrites the first, a lost update. The standard remedy is optimistic concurrency: a version column the ORM checks and increments on update, so a stale write fails and the app can retry or surface a conflict.
ONE CONCRETE EXAMPLE Two editors load product version 5. Editor A saves first; the row becomes version 6. Editor B then saves, but the ORM's UPDATE includes WHERE version = 5, matches zero rows, and raises a stale-data exception, preventing B from silently clobbering A's change. Without the version check, B's stale session would overwrite A's edit unnoticed.
Read the original → martinfowler.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.