Skip to content

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:

  1. Productivity — no raw SQL, work with objects
  2. Type safety — model classes provide types (in TypeScript)
  3. Migrations — generate schema changes from model changes
  4. Relations — easily load related data (with caveats like N+1)

Drawbacks:

  1. Performance — generated SQL may be suboptimal
  2. N+1 problem — lazy loading causes extra queries
  3. Abstraction leak — complex queries need raw SQL anyway
  4. Learning curve — ORM-specific APIs

Popular ORMs: Prisma (TypeScript), SQLAlchemy (Python), Hibernate (Java), Entity Framework (C#), Sequelize (Node.js).

Example

javascript
// 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 queries

ORM 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

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary