Object-relational mapping

Also known as: ORM · object-relational mapper

On this page 7

Object-relational mapping (ORM) is a programming technique that maps classes and objects to tables and rows in a relational database, so developers can create, read, update and delete data through objects instead of writing every SQL statement by hand. In databases, an object-relational mapper is the library that implements this technique, such as Hibernate, Entity Framework Core, SQLAlchemy or Django ORM.

ORM exists to bridge the object-relational impedance mismatch: object models use identity, references, inheritance and collections, while the relational model uses keys, joins, sets of rows and declarative queries. The mapper absorbs this difference, but it never removes it entirely, which is why understanding the generated SQL remains essential.

How an object-relational mapper works

An object-relational mapper works by holding mapping metadata that links each class to a table, each attribute to a column and each object reference to a foreign key. Metadata is declared through annotations, attributes, configuration files or code conventions, and the mapper uses it to generate SQL statements and to turn result sets back into objects, a step called hydration or materialization.

Most full-featured mappers rely on a set of well-known patterns. The unit of work tracks which objects changed during a business transaction and writes all changes in one flush, while the identity map guarantees that one database row is represented by only one object instance within a session.

MechanismWhat it doesPractical effect
Mapping metadataLinks classes, fields and relations to schemaDefines table, column and key usage
Change trackingDetects modified, new and deleted objectsGenerates only the needed UPDATE statements
Unit of workBatches changes into one commitKeeps writes consistent within a transaction
Identity mapCaches one object per primary keyPrevents duplicate, conflicting instances
Lazy loadingFetches related data on first accessSaves queries but risks hidden round trips
Query translationConverts object queries into SQLSupports portability across DBMS dialects
Core mechanisms inside a typical mapper

Queries are expressed through an object query language or builder, for example LINQ in .NET, JPQL or the Criteria API in Java, or the expression language of SQLAlchemy. The mapper translates these into the SQL dialect of the target DBMS, which provides a degree of database portability.

Active record, data mapper and lighter alternatives

ORM implementations follow two main architectural patterns, and the choice shapes how domain code relates to persistence. In the active record pattern, each object knows how to save and load itself; in the data mapper pattern, a separate layer moves data between objects and tables, keeping domain classes unaware of the database.

ApproachHow persistence worksTypical examplesBest fit
Active recordModel classes save themselvesRails Active Record, EloquentCRUD-heavy applications
Data mapperSeparate mapper and sessionHibernate, SQLAlchemy ORM, DoctrineRich domain models
Micro-ORMHand-written SQL, automatic hydrationDapper, sqlxPerformance-critical reads
Query builderComposable SQL without object mappingjOOQ, Knex, SQLAlchemy CoreComplex reporting queries
Raw SQLDirect statements through a driverJDBC, psycopgBulk operations and tuning
Approaches to data access in application code

Many systems mix these approaches. A common design uses the full ORM for transactional CRUD and switches to hand-written SQL or a query builder for reporting, bulk updates and analytics, where set-based operations matter more than object identity.

Mapping relational concepts to objects

Each relational concept has an object-side counterpart, and a correct mapping depends on knowing how the mapper represents keys, relations and constraints. Primary keys become identifiers, foreign keys become object references or collections, and junction tables become many-to-many associations.

Relational conceptObject-side representationPoint of attention
Primary keyIdentifier propertyChoose generation strategy carefully
Foreign keyReference to another objectDefine cascade and delete rules
One-to-many relationCollection on the parentWatch loading strategy and ordering
Junction tableMany-to-many associationPromote to an entity if it carries data
NULLOptional or nullable propertyAlign nullability with constraints
InheritanceSingle, joined or per-class tablesEach strategy trades joins for sparsity
How relational structures appear in an object model

Inheritance has no native relational equivalent, so mappers offer single-table, joined-table and table-per-class strategies. Single-table mapping is fastest to query but leaves many NULL columns, while joined-table mapping is normalized but requires additional joins on every read.

Performance pitfalls and how to avoid them

The most serious ORM risks are performance problems that remain invisible in application code and appear only under production data volumes. The classic example is the N+1 query problem: loading 100 orders and then lazily reading each customer can produce 101 queries instead of one or two.

ProblemCauseRemedy
N+1 queriesLazy loading inside loopsEager fetch joins or batch loading
Over-fetchingLoading whole entities for a list viewProject only the needed columns
Bloated sessionsTracking thousands of objectsUse read-only queries or clear the session
Slow bulk writesRow-by-row inserts and updatesUse batch inserts or set-based SQL
Missing indexesGenerated queries on unindexed columnsReview query plans and add indexes
Frequent ORM performance problems and their remedies

The decisive habit is to log and review the generated SQL during development, and to inspect execution plans for critical paths. Teams should also keep transactions short, because a long-lived session holds locks and stale objects, and they should configure optimistic locking with a version column where concurrent edits are possible.

When ORM is the right choice

ORM is the right choice when an application performs mostly transactional CRUD operations on a well-structured schema and benefits from a domain model. It reduces boilerplate, centralizes mapping rules, provides parameterized queries that prevent most SQL injection, and integrates with schema migration tools.

  • Prefer a full ORM for business applications with rich entities and moderate data volumes.
  • Prefer SQL or a query builder for analytics, complex aggregations and large batch jobs.
  • Avoid relying on ORM portability as a guarantee, because dialect-specific behavior still leaks through.
  • Treat the mapper as a productivity tool, not a substitute for understanding relational design.

The short version

Programs think in terms of things such as customers, orders and products, while databases store information in tables of rows and columns. Object-relational mapping acts as a translator between those two ways of organizing data.

A developer can say save this customer, and the mapper writes the correct database command automatically. This saves a great deal of repetitive work. The catch is that an automatic translation is not always the most efficient one, so experienced developers still check what the translator actually sends to the database.

Where it makes a difference

An online bookstore built with an ORM noticed that its order history page took about four seconds to load for active customers. Logging the generated SQL showed that the page loaded 50 orders and then lazily fetched the items and book titles for each order separately, producing more than 150 queries per request.

The developers changed the query to eagerly load order items and books with join fetching and limited the result to the columns shown on the page. The page then needed only two queries and loaded in roughly 200 milliseconds. For the nightly price update, which touches 300,000 rows, the team replaced the object loop with a single set-based SQL statement, cutting the job from 40 minutes to under one minute while keeping the ORM for everyday transactions.