Search This Blog

Monday, August 02, 2010

Persistence Patterns

A domain model is an object model of the domain that incorporates both behavior and data. A Domain Model creates a web of interconnected objects, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line on an order form. The business objects in the middle tier and the user interface or service layer are the application, and the database is a means to reliably persist the state of the business objects between sessions.

An Active Record approach puts persistence methods directly onto the entity object. In this case, the Address class would probably have methods like Save, Update, and Delete, as well as a static Load method that queries the database for an Address object. Active Record is best for systems with simpler domain logic, CRUD-intensive applications.


The Data Mapper pattern strips most of the responsibility of persistence from the entity objects in favor of classes external to the entities. With a Data Mapper pattern, you access, query, and save entity objects with some kind of repository.

Repository pattern mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects. Repository pattern put a façade over your persistence system so that you can shield the rest of your application code from having to know how persistence works.

In persistence tooling, preventing duplicate logical references is the job of the Identity Map pattern. An Identity Map ensures that each object gets loaded only once by keeping every loaded object in a map and looks up objects using the map when referring to them.

According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.”. Your Unit of Work class will have methods to mark entities as changed, new, or deleted. The Unit of Work will also have methods to commit or roll back all of the changes. One of the best ways to use the Unit of Work pattern is to allow disparate classes and services to take part in a single logical transaction.

No comments: