Introduction
Chapter 1: Introduction to TypeORM
Section titled “Chapter 1: Introduction to TypeORM”Understanding the Foundation of TypeORM
Section titled “Understanding the Foundation of TypeORM”1.1 What is TypeORM?
Section titled “1.1 What is TypeORM?”TypeORM is an Object-Relational Mapping (ORM) library for TypeScript and JavaScript that enables developers to work with databases using objects instead of writing raw SQL queries.
TypeORM Overview ================================================================================
+---------------------------+ | Your Application | | (TypeScript/JavaScript) | +---------------------------+ | | Objects/Entities v +---------------------------+ | TypeORM | | +---------------------+ | | | Entity Manager | | | +---------------------+ | | | Query Builder | | | +---------------------+ | | | Repository | | | +---------------------+ | | | Migrations | | | +---------------------+ | +---------------------------+ | | Translates to SQL v +---------------------------+ | Database | | (PostgreSQL/MySQL/etc.) | +---------------------------+
================================================================================Key Features
Section titled “Key Features”| Feature | Description |
|---|---|
| Type-Safe | Full TypeScript support with decorators |
| Multiple Databases | MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, MongoDB |
| Active Record & Data Mapper | Supports both patterns |
| Query Builder | Flexible and powerful query construction |
| Migrations | Database schema versioning |
| Relations | One-to-One, One-to-Many, Many-to-Many |
| Lazy Relations | Load related data on demand |
| Subscribers | Event-driven architecture |
1.2 Why Use TypeORM?
Section titled “1.2 Why Use TypeORM?”Without TypeORM (Raw SQL)
Section titled “Without TypeORM (Raw SQL)” Raw SQL Approach +------------------------------------------------------------------+ | | | const userId = 1; | | | | // Manual SQL query construction | | const query = ` | | SELECT u.*, p.title, p.content | | FROM users u | | LEFT JOIN posts p ON u.id = p.authorId | | WHERE u.id = ${userId} | | `; | | | | // No type safety | | const result = await database.query(query); | | | | // Manual mapping | | const user = { | | id: result[0].id, | | name: result[0].name, | | posts: result.map(r => ({ | | title: r.title, | | content: r.content | | })) | | }; | | | | Problems: | | - SQL injection risk | | - No type safety | | - Manual object mapping | | - Hard to maintain | | - No schema validation | | | +------------------------------------------------------------------+With TypeORM
Section titled “With TypeORM” TypeORM Approach +------------------------------------------------------------------+ | | | // Type-safe entity | | const user = await userRepository.findOne({ | | where: { id: 1 }, | | relations: ['posts'] | | }); | | | | // Full TypeScript support | | console.log(user.name); // Type-checked! | | console.log(user.posts[0].title); // Type-checked! | | | | Benefits: | | - Type safety throughout | | - Automatic object mapping | | - SQL injection protection | | - Easy to maintain | | - Schema validation | | | +------------------------------------------------------------------+1.3 Architecture Patterns
Section titled “1.3 Architecture Patterns”TypeORM supports two primary patterns for data access:
Active Record Pattern
Section titled “Active Record Pattern” Active Record Pattern +------------------------------------------------------------------+ | | | Entity contains both data and database methods | | | | +----------------------------------------------------------+ | | | User Entity | | | | | | | | Properties: Methods: | | | | - id - save() | | | | - name - remove() | | | | - email - find() | | | | - password - findOne() | | | | - delete() | | | | | | | +----------------------------------------------------------+ | | | | Usage: | | +----------------------------------------------------------+ | | | | | | | const user = new User(); | | | | user.name = 'John'; | | | | user.email = 'john@example.com'; | | | | await user.save(); // Method on entity | | | | | | | | const users = await User.find(); | | | | | | | +----------------------------------------------------------+ | | | | Best for: Simple applications, quick prototyping | | | +------------------------------------------------------------------+Data Mapper Pattern
Section titled “Data Mapper Pattern” Data Mapper Pattern +------------------------------------------------------------------+ | | | Entity contains only data, Repository handles operations | | | | +-------------------+ +-------------------+ | | | User Entity | | Repository | | | | | | | | | | Properties: | | Methods: | | | | - id | | - save() | | | | - name | | - find() | | | | - email | | - findOne() | | | | - password | | - delete() | | | | | | - create() | | | +-------------------+ +-------------------+ | | | | Usage: | | +----------------------------------------------------------+ | | | | | | | const user = new User(); | | | | user.name = 'John'; | | | | user.email = 'john@example.com'; | | | | | | | | await userRepository.save(user); // Via repository | | | | | | | | const users = await userRepository.find(); | | | | | | | +----------------------------------------------------------+ | | | | Best for: Enterprise applications, Clean Architecture | | | +------------------------------------------------------------------+1.4 TypeORM vs Other ORMs
Section titled “1.4 TypeORM vs Other ORMs” ORM Comparison +------------------------------------------------------------------+ | | | Feature | TypeORM | Prisma | Sequelize | | ------------------|------------|-----------|------------------| | TypeScript First | Yes | Yes | No | | Decorators | Yes | No | No | | Query Builder | Excellent | Good | Good | | Migrations | Built-in | Built-in | Built-in | | Active Record | Yes | No | Yes | | Data Mapper | Yes | Yes | No | | Raw SQL | Easy | Moderate | Easy | | Relations | Excellent | Excellent | Good | | Performance | Good | Good | Good | | Documentation | Good | Excellent | Good | | | +------------------------------------------------------------------+1.5 TypeORM Ecosystem
Section titled “1.5 TypeORM Ecosystem” TypeORM Ecosystem ================================================================================
TypeORM Core | +----------------------------+----------------------------+ | | | | | v v v v v +------------+ +------------+ +------------+ +------------+ +--------+ | CLI Tool | | Migrations | | CLI | | Extensions | | Docs | | | | | | Commands | | | | | | - Generate | | - Create | | - schema: | | - TypeORM | | - API | | - Create | | - Run | | sync | | Module | | - Docs | | - Run | | - Revert | | - schema: | | (NestJS) | | - Ex | | | | | | drop | | | | | +------------+ +------------+ +------------+ +------------+ +--------+
================================================================================TypeORM CLI Commands
Section titled “TypeORM CLI Commands”# Initialize new TypeORM projecttypeorm init --name my-project --database postgres
# Generate entitytypeorm entity:create -n User
# Generate migrationtypeorm migration:create -n CreateUserTable
# Run migrationstypeorm migration:run
# Revert last migrationtypeorm migration:revert
# Sync schema (development only!)typeorm schema:sync
# Drop schematypeorm schema:drop1.6 When to Use TypeORM
Section titled “1.6 When to Use TypeORM”Good Use Cases
Section titled “Good Use Cases” Recommended Scenarios +------------------------------------------------------------------+ | | | +------------------+ | | | NestJS Projects | - First-class integration | | +------------------+ | | | | +------------------+ | | | Complex Domains | - Rich relationship handling | | +------------------+ | | | | +------------------+ | | | TypeScript Apps | - Type safety throughout | | +------------------+ | | | | +------------------+ | | | Multi-Database | - Same API for different DBs | | +------------------+ | | | | +------------------+ | | | Enterprise Apps | - Migrations, transactions | | +------------------+ | | | +------------------------------------------------------------------+Consider Alternatives When
Section titled “Consider Alternatives When” Alternative Scenarios +------------------------------------------------------------------+ | | | +--------------------+ | | | Simple Queries Only | - Consider raw query builders | | +--------------------+ - pg, mysql2 directly | | | | +--------------------+ | | | Maximum Performance | - Consider query builders | | +--------------------+ - Kysely, Slonik | | | | +--------------------+ | | | No-SQL Primary | - TypeORM MongoDB support limited | | +--------------------+ - Consider Mongoose, Prisma | | | | +--------------------+ | | | Learning Curve | - Consider Prisma for simplicity | | +--------------------+ | | | +------------------------------------------------------------------+1.7 TypeORM Project Structure
Section titled “1.7 TypeORM Project Structure” Typical TypeORM Project +------------------------------------------------------------------+ | | | src/ | | ├── entities/ | | │ ├── User.ts | | │ ├── Post.ts | | │ └── Comment.ts | | │ | | ├── repositories/ | | │ ├── UserRepository.ts | | │ └── PostRepository.ts | | │ | | ├── migrations/ | | │ ├── 1234567890-CreateUser.ts | | │ └── 1234567891-CreatePost.ts | | │ | | ├── subscribers/ | | │ └── UserSubscriber.ts | | │ | | ├── data-source.ts | | └── index.ts | | | +------------------------------------------------------------------+1.8 TypeORM Flow
Section titled “1.8 TypeORM Flow” TypeORM Request Flow ================================================================================
1. Define Entity 2. Create Repository +------------------+ +------------------+ | @Entity() | | @EntityRepository| | class User { | | class UserRepo | | @PrimaryColumn | | extends Repo | | id: number; | | { | | | | findByName() | | @Column() | | } | | name: string; | +------------------+ +------------------+ | | | | v v 3. TypeORM Creates Table 4. Use in Application +------------------+ +------------------+ | users | | const users = | | -------- | | await userRepo | | id (PK) | | .find(); | | name | +------------------+ +------------------+
================================================================================1.9 Key Concepts Summary
Section titled “1.9 Key Concepts Summary” TypeORM Key Concepts +------------------------------------------------------------------+ | | | Concept | Description | | -----------------|------------------------------------------- | | Entity | Class mapped to database table | | Column | Property mapped to table column | | Primary Column | Primary key column | | Repository | Data access object for entity | | Query Builder | Programmatic SQL query construction | | Migration | Database schema version control | | Relation | Connection between entities | | Subscriber | Entity lifecycle event listener | | DataSource | Database connection configuration | | Transaction | Atomic database operations | | | +------------------------------------------------------------------+1.10 Installation Overview
Section titled “1.10 Installation Overview”# Install TypeORM and database drivernpm install typeorm reflect-metadata
# Choose your database drivernpm install pg # PostgreSQLnpm install mysql2 # MySQLnpm install sqlite3 # SQLitenpm install better-sqlite3 # SQLite (better performance)npm install mongodb # MongoDB
# For NestJS integrationnpm install @nestjs/typeorm @nestjs/configNext Chapter
Section titled “Next Chapter”Chapter 2: TypeScript Foundations for TypeORM
Last Updated: February 2026