🗄️ Databases

ORM

Object-Relational Mapping

A technique for mapping objects to relational DBs. No need to write SQL directly. Prisma, SQLAlchemy, TypeORM.

📖 Detailed Explanation

What is an ORM?

ORM (Object-Relational Mapping) is a technology that automatically maps objects in an object-oriented programming language to tables in a relational database. It allows developers to manipulate the database with programming language code without writing SQL directly.

Advantages of ORM

  • Improved productivity: No need to write repetitive CRUD SQL
  • DB independence: Easy to switch to a different DBMS
  • Type safety: Errors are detected at compile time
  • Maintainability: Code readability and object-oriented design
  • Security: Defense against SQL Injection (automatic escaping)

Disadvantages of ORM

  • Performance overhead: Generates inefficient SQL for complex queries
  • N+1 problem: A surge of queries when retrieving related data
  • Learning cost: The ORM itself has to be learned
  • Limits on complex queries: There are cases where native SQL is needed

Major ORM Libraries

  • Python: SQLAlchemy, Django ORM, Peewee
  • JavaScript/TypeScript: Prisma, TypeORM, Sequelize, Drizzle
  • Java: Hibernate, JPA, MyBatis
  • Ruby: Active Record
  • Go: GORM, Ent

Active Record vs Data Mapper

  • Active Record: The object is responsible for DB operations directly (Django ORM, Rails Active Record)
  • Data Mapper: A separate mapper separates the object from the DB (SQLAlchemy, TypeORM)

💻 Code Example

SQLAlchemy (Python)

Python
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.orm import declarative_base, relationship, sessionmaker

Base = declarative_base()

# 모델 정의
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False)
    email = Column(String(100), unique=True)

    orders = relationship('Order', back_populates='user')

class Order(Base):
    __tablename__ = 'orders'

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    total = Column(Integer)

    user = relationship('User', back_populates='orders')

# 세션 생성
engine = create_engine('postgresql://localhost/mydb')
Session = sessionmaker(bind=engine)
session = Session()

# CRUD 연산
# Create
user = User(name='Alice', email='alice@example.com')
session.add(user)
session.commit()

# Read
user = session.query(User).filter_by(email='alice@example.com').first()
users = session.query(User).filter(User.name.like('%Al%')).all()

# Update
user.name = 'Alice Kim'
session.commit()

# Delete
session.delete(user)
session.commit()

Prisma (TypeScript)

Prisma Schema
// schema.prisma
model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  orders    Order[]
  createdAt DateTime @default(now())
}

model Order {
  id        Int      @id @default(autoincrement())
  total     Int
  user      User     @relation(fields: [userId], references: [id])
  userId    Int
}
TypeScript
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// Create
const user = await prisma.user.create({
  data: {
    email: 'alice@example.com',
    name: 'Alice',
    orders: {
      create: [
        { total: 50000 },
        { total: 30000 }
      ]
    }
  },
  include: { orders: true }
})

// Read with relations
const users = await prisma.user.findMany({
  where: {
    email: { contains: 'example.com' }
  },
  include: {
    orders: {
      where: { total: { gte: 10000 } }
    }
  },
  orderBy: { createdAt: 'desc' },
  take: 10
})

// Transaction
await prisma.$transaction(async (tx) => {
  const user = await tx.user.update({
    where: { id: 1 },
    data: { name: 'Alice Kim' }
  })

  await tx.order.create({
    data: { userId: user.id, total: 100000 }
  })
})

The N+1 Problem and Its Solution

Python (Problem)
# N+1 문제 발생 (1번 유저 쿼리 + N번 주문 쿼리)
users = session.query(User).all()
for user in users:
    print(user.orders)  # 매번 추가 쿼리 발생!
Python (Solution)
from sqlalchemy.orm import joinedload, selectinload

# Eager Loading으로 해결
# 1. joinedload: JOIN으로 한 번에 가져오기
users = session.query(User).options(joinedload(User.orders)).all()

# 2. selectinload: IN 절로 별도 쿼리 (추천)
users = session.query(User).options(selectinload(User.orders)).all()

Using Raw SQL

Python (SQLAlchemy)
from sqlalchemy import text

# ORM으로 어려운 복잡한 쿼리는 Raw SQL 사용
result = session.execute(text("""
    SELECT u.name, COUNT(o.id) as order_count, SUM(o.total) as total_spent
    FROM users u
    LEFT JOIN orders o ON u.id = o.user_id
    WHERE o.created_at >= :start_date
    GROUP BY u.id
    HAVING COUNT(o.id) > 5
    ORDER BY total_spent DESC
"""), {'start_date': '2024-01-01'})

for row in result:
    print(row.name, row.order_count, row.total_spent)

💬 Real-world conversation examples

Junior Developer
"If I use an ORM, don't I need to learn SQL?"
Senior developer
"No, you actually need to know SQL even better. You have to understand the queries the ORM generates to solve performance problems. For complex queries you'll have to use Raw SQL anyway. An ORM is just a tool."
Backend developer
"The API suddenly got slow and I can't figure out why."
DBA
"Looking at the logs, over 100 queries are being sent. It's a classic N+1 problem. Apply Eager Loading where related data is retrieved. Try joinedload or selectinload."
Team lead
"Which ORM should we use for the new project? I'm torn between TypeORM and Prisma."
Senior developer
"Prisma has much better type safety. Migrations are also generated automatically when the schema changes. However, it has limitations with complex queries, so you may need to use Raw SQL alongside it. Choose based on the project's complexity."

⚠️ Cautions

⚠️ Always Watch Out for the N+1 Problem
Be careful about N+1 queries occurring when retrieving related data. Always check the query logs and use Eager Loading (joinedload, include, etc.) appropriately. It is the most common cause of performance problems.
⚠️ Check the Generated SQL
Be sure to check the SQL that the ORM generates. Turn on query logging in the development environment and monitor whether inefficient queries are being generated. Also check the execution plan with EXPLAIN.
⚠️ Transaction Scope
Define the session/transaction scope clearly. If a transaction is too long, lock contention occurs; if it is too short, data inconsistency occurs. Handle external API calls outside the transaction.
⚠️ Use the Bulk API for Large Operations
When processing a lot of data, do not create ORM objects one by one. Use a Bulk API such as bulk_insert or bulk_update, or use Raw SQL to ensure performance.

🔗 Related Terms

📚 Learn More