Object-Relational Mapping (ORM)

Object-Relational Mapping (ORM) is a software layer that moves data between in-memory objects and the tables of a relational database, letting application developers work with objects and their fields rather than hand-writing SQL for every read and write. Two of the foundational patterns behind ORMs are catalogued in Martin Fowler’s “Patterns of Enterprise Application Architecture”: Data Mapper, “a layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself,” and Active Record, “an object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.”

The reason ORMs exist, and the reason they are hard, is that the two sides do not line up. In his essay “OrmHate,” Fowler describes the task as “synchronizing between two quite different representations of data, one in the relational database, and the other in-memory.” In-memory structures with references, inheritance, and collections do not correspond cleanly to flat rows and foreign keys; this gap is commonly called the object-relational impedance mismatch.

Fowler argues the mismatch is intrinsic and would exist even without objects: “Although this is usually referred to as object-relational mapping, there is really nothing to do with objects here. By rights it should be referred to as in-memory/relational mapping problem.” An ORM hides that work, which is convenient, but the abstraction can leak. A well-known pitfall is the N+1 query problem, where iterating over a collection of mapped objects silently issues one extra query per item.

Despite the criticism, Fowler’s position is that ORMs solve a genuinely difficult problem better than most hand-rolled alternatives, and deserve more credit than the “snarky remarks” they tend to attract.