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:
Article.objects.filter(year=2020).select_related('author')# SELECT ... FROM article# JOIN author ON author.id = article.author_id# WHERE article.year = 2020Besides 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 pagesVerified 9 Nov