ORM (Object-Relational Mapper)
In one line
ORM maps database tables to objects — write code in your language instead of SQL, with automatic query generation.
In simple words
An Object-Relational Mapper (ORM) translates between database tables and programming language objects. You define model classes, and the ORM handles SQL generation, connection management, and result mapping.
Benefits:
- Productivity — no raw SQL, work with objects
- Type safety — model classes provide types (in TypeScript)
- Migrations — generate schema changes from model changes
- Relations — easily load related data (with caveats like N+1)
Drawbacks:
- Performance — generated SQL may be suboptimal
- N+1 problem — lazy loading causes extra queries
- Abstraction leak — complex queries need raw SQL anyway
- Learning curve — ORM-specific APIs
Popular ORMs: Prisma (TypeScript), SQLAlchemy (Python), Hibernate (Java), Entity Framework (C#), Sequelize (Node.js).
Example
// Prisma ORM example (TypeScript)
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// Define schema in schema.prisma:
// model User {
// id Int @id @default(autoincrement())
// name String
// posts Post[]
// }
// model Post { id Int @id; title String; author User @relation(fields: [authorId]) }
// ORM generates type-safe queries
const users = await prisma.user.findMany({
include: { posts: true }, // eager load relations
where: { name: { contains: 'Ada' } },
orderBy: { id: 'desc' },
});
// users is typed: (User & { posts: Post[] })[]
// No SQL written — ORM generates optimized queriesORM maps tables to model classes. You write code with objects and relations; the ORM generates SQL. Prisma provides type safety and auto-completion.
Common confusions
Confused with: query builder
The difference: An ORM maps tables to objects and handles the full lifecycle (relations, migrations, identity map). A query builder just constructs SQL programmatically (e.g., Knex.js) without object mapping. ORMs are higher-level; query builders are lower-level and closer to SQL.
Related terms
Related Resources
Related Lessons
- ORMs
ORM overview.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.