Part 0 · 2 chapters · ~12 min

The Impedance Mismatch

The formal mismatch between objects and relations (identity, inheritance, associations, granularity, navigation), the history from TopLink and Hibernate to ActiveRecord and the Rails effect, Fowler's patterns vocabulary, Data Mapper against Active Record, and the ORM debate argued properly in both directions.

1

Objects and tables disagree

Ted Neward called ORMs "the Vietnam of computer science": a project that starts easy and gets harder the deeper you go. The fair version: ORMs remove large amounts of repetitive code and make the common 90% pleasant, and they hide the costs of the remaining 10%. Engineers who know the machinery get both benefits.

THE OBJECT-RELATIONAL IMPEDANCE MISMATCH
where objects and tables disagree
identityObjects are identified byreference; rows by primary key.Two loads, two objects, one row?inheritanceClasses inherit; tables do not.Single table, table per class, orjoined tables?associationsObjects hold references both ways;tables hold foreign keys one way,plus join tables.granularityA Money value object has no table;an Address may be columns inseveral tables.navigationObjects are walked one referenceat a time; SQL wants sets in onequery.transactionsObjects change in memory freely;databases need explicit, shorttransactions.
swipe the figure sideways, or tap expand for full screen
1/5
identity
Loading the same row twice can give two different objects that disagree after one is modified. ORMs solve this with an identity map (part 1).
reference identity vs primary keyidentity maps resolve it
2

Data Mapper versus Active Record

Active RecordData Mapper
ideaan object wraps a row and knows how to save itself (account.save)plain domain objects; a separate mapper or session persists them
examplesRails ActiveRecord, Django ORM, Sequelize, Laravel EloquentHibernate/JPA, SQLAlchemy ORM, MikroORM, Doctrine
strengthssimple, fast to start, conventionsdomain model independent of persistence; unit of work batches changes
costsdomain logic coupled to tables; testing needs the databasemore concepts (sessions, flush, detached objects)

Martin Fowler's Patterns of Enterprise Application Architecture (2002) named the vocabulary used for the rest of this course: Identity Map, Unit of Work, Lazy Load, Data Mapper, Active Record, Repository, Query Object.