Bookmarks

ORM — object-relational mapping

A layer between a relational database and object-oriented code: tables map to classes, rows to objects, and the ORM generates the SQL queries itself.

Also: ORM library, ORM framework

checked 9 Nov

All terms

An application stores data in tables but works with it as objects. An ORM handles the translation between the two: the developer describes classes and relationships, and the library generates SQL and turns result rows back into objects.

How it works

The mismatch between objects and tables is so common that it has its own name, the object/relational impedance mismatch: the relational model stores data as rows, while an object language uses linked objects with inheritance. ORMs were created to bridge this gap. Examples are Django ORM in Python, Hibernate in Java, SQLAlchemy, Entity Framework in .NET and Active Record in Ruby on Rails.

A class maps to a table, a field to a column, and a one-to-many relationship to a foreign key. Queries are written with language constructs instead of SQL strings:

pythonDjango ORM: a method call and roughly the SQL it produces
Article.objects.filter(year=2020).select_related('author')# SELECT ... FROM article# JOIN author ON author.id = article.author_id# WHERE article.year = 2020

Besides queries, an ORM usually provides migrations, which create and change the schema from the model definitions; parameterised queries, which protect against SQL injection; and transactions and model-level validation.

The N+1 problem

The best-known ORM pitfall is the N+1 query. Code accesses a related object in a loop, and lazy loading runs one query per row: a list of 100 articles with author names takes 101 queries instead of one with a JOIN. The fix is eager loading: select_related and prefetch_related in Django, JOIN FETCH in Hibernate, includes in Rails.

When an ORM is not a good fit

  • reports and analytics: complex aggregates, window functions and CTEs are easier to read in plain SQL
  • bulk inserts and updates: an ORM spends noticeably more time and memory per row
  • database-specific features that the library does not support

That is why a typical project combines both approaches: ordinary operations go through the ORM, heavy queries are written by hand, using the same parameterisation where needed.

Sources

the term is written from these pages

Verified 9 Nov

Not to be confused with

what it is mixed up with and how it differs

  • CRUDCRUD operations

    CRUD is a set of data operations: create, read, update, delete. An ORM is a way to map code objects to tables, and it is usually how CRUD is carried out.

In depth in the references

where the topic is covered in detail