TypeORM Introduction and Basic Usage
TypeORM is an Object-Relational Mapping (ORM) framework designed for TypeScript and JavaScript, enabling object-oriented interaction with relational databases while maintaining type safety. It supports multiple databases, including MySQL, PostgreSQL, SQLite, SQL Server, and more.
TypeORM Overview
Key features of TypeORM include:
- Type Safety: Seamlessly integrates with TypeScript, providing comprehensive type definitions for robust and maintainable code.
- Entities: Uses entities (TypeScript classes) to represent database tables.
- Migrations: Supports database migrations to automatically create or update database schemas, streamlining development.
- Query Builder: Offers a powerful query builder for constructing complex SQL queries while keeping code clean and readable.
- Relationship Management: Supports one-to-one, one-to-many, and many-to-many relationships for easy entity associations.
- Transaction Handling: Provides transaction support to ensure atomicity of operations.
Installation and Setup
Assuming you have a Node.js project with TypeScript installed, install TypeORM and the appropriate database driver (e.g., for MySQL):
npm install typeorm reflect-metadata mysql2Configuration
Create an ormconfig.json file in the project root to configure the database connection:
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "yourpassword",
"database": "yourdbname",
"entities": ["src/entities/*.ts"],
"migrations": ["src/migrations/*.ts"],
"cli": {
"migrationsDir": "src/migrations"
}
}Creating an Entity
Entities are TypeScript classes that map to database tables. Example of a user entity:
// src/entities/User.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
}Database Migrations
TypeORM provides a CLI tool for generating and running migrations. Generate a new migration file:
typeorm migration:create -n CreateUserTableEdit the generated migration file to define the user table creation logic, then run the migration:
typeorm migration:runCRUD Operations
Create a Record
import { getRepository } from 'typeorm';
import { User } from './entities/User';
const userRepository = getRepository(User);
const user = new User();
user.username = 'john.doe';
user.password = 'secret';
await userRepository.save(user);Read a Record
const userRepository = getRepository(User);
const user = await userRepository.findOne({ where: { id: 1 } });
console.log(user);Update a Record
const userRepository = getRepository(User);
const user = await userRepository.findOne({ where: { id: 1 } });
user.username = 'newname';
await userRepository.save(user);Delete a Record
const userRepository = getRepository(User);
const user = await userRepository.findOne({ where: { id: 1 } });
await userRepository.remove(user);Query Builder
Use the query builder for complex queries:
const userRepository = getRepository(User);
const users = await userRepository
.createQueryBuilder('user')
.where('user.id > :id', { id: 10 })
.orderBy('user.username', 'ASC')
.getMany();TypeORM DataSource
Creating and Using a DataSource
The DataSource is the core component in TypeORM for managing database connections. It initializes connections, manages entities, migrations, and event subscriptions.
1: Install Dependencies
Ensure TypeORM and the database driver are installed. For MySQL:
npm install typeorm mysql22: Configure the DataSource
Create a configuration file (e.g., ormconfig.js or ormconfig.json). Example using ormconfig.js:
// ormconfig.js
module.exports = {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'testdb',
entities: ['dist/**/*.entity{.ts,.js}'],
migrations: ['dist/migrations/*{.ts,.js}'],
subscribers: ['dist/subscribers/*{.ts,.js}'],
synchronize: false,
logging: false,
cli: {
entitiesDir: 'src/entities',
migrationsDir: 'src/migrations',
subscribersDir: 'src/subscribers'
}
};3: Create a DataSource Instance
Initialize a DataSource instance using the configuration:
import { DataSource } from 'typeorm';
import ormconfig from './ormconfig';
const dataSource = new DataSource(ormconfig);
await dataSource.initialize();Alternatively, define the configuration directly:
import { createDataSource } from 'typeorm';
const dataSource = await createDataSource({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'testdb',
entities: ['dist/**/*.entity{.ts,.js}'],
migrations: ['dist/migrations/*{.ts,.js}'],
});
await dataSource.initialize();4: Use the DataSource
The initialized DataSource provides methods for database operations:
- EntityManager: For CRUD operations.
- Repository: Entity-specific operations.
- QueryRunner: For transactions and complex queries.
Using EntityManager
const entityManager = dataSource.manager;
const user = new User();
user.name = 'John Doe';
await entityManager.save(user);Using Repository
const userRepository = dataSource.getRepository(User);
const user = await userRepository.findOne({ where: { name: 'John Doe' } });Using QueryRunner
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const user = new User();
user.name = 'John Doe';
await queryRunner.manager.save(user);
await queryRunner.commitTransaction();
} catch (error) {
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}5: Close the DataSource
Close the DataSource to release resources when no longer needed:
await dataSource.destroy();DataSource Options
The DataSourceOptions object configures the database connection. Key options include:
type: Database type (e.g., ‘mysql’, ‘postgres’, ‘sqlite’, ‘mssql’).host: Database server hostname or IP.port: Database server port.usernameandpassword: Database credentials.database: Database name.entities: Paths to entity classes.migrations: Paths to migration files.subscribers: Paths to event subscriber classes.synchronize: Iftrue, syncs entities with the database schema on startup (set tofalsein production).logging: Controls logging (boolean, string array, or function).cache: Enables query caching.ssl: SSL/TLS configuration.replication: Master-slave replication setup.extra: Driver-specific options.cli: CLI tool configuration.
Example Configuration
const dataSourceOptions = {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'mydatabase',
entities: ['dist/**/*.entity{.ts,.js}'],
migrations: ['dist/migrations/*{.ts,.js}'],
subscribers: ['dist/subscribers/*{.ts,.js}'],
synchronize: false,
logging: false,
extra: {
charset: 'utf8mb4_unicode_ci'
},
cache: {
duration: 1000,
alwaysEnabled: true
},
ssl: {
rejectUnauthorized: false
},
replication: {
master: {
host: 'master-db.example.com',
port: 3306,
username: 'replica',
password: 'replicapassword',
database: 'mydatabase'
},
slaves: [
{
host: 'slave-db1.example.com',
port: 3306,
username: 'replica',
password: 'replicapassword',
database: 'mydatabase'
},
{
host: 'slave-db2.example.com',
port: 3306,
username: 'replica',
password: 'replicapassword',
database: 'mydatabase'
}
]
},
cli: {
entitiesDir: 'src/entities',
migrationsDir: 'src/migrations',
subscribersDir: 'src/subscribers'
}
};Using DataSource Options
import { DataSource } from 'typeorm';
const dataSource = new DataSource(dataSourceOptions);
await dataSource.initialize();Multiple DataSources
Understanding Multiple DataSources
Each DataSource instance represents an independent database connection, allowing connections to different databases or schemas within the same database.
Creating Multiple DataSources
import { DataSource } from 'typeorm';
const dataSource1 = new DataSource({
type: 'mysql',
host: 'db1.example.com',
port: 3306,
username: 'user1',
password: 'pass1',
database: 'db1',
entities: ['dist/entities/db1/*.entity{.ts,.js}'],
});
const dataSource2 = new DataSource({
type: 'mysql',
host: 'db2.example.com',
port: 3306,
username: 'user2',
password: 'pass2',
database: 'db2',
entities: ['dist/entities/db2/*.entity{.ts,.js}'],
});Database Schemas
In PostgreSQL, schemas are namespaces for organizing database objects. TypeORM supports specifying schemas in the configuration:
const dataSource = new DataSource({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'password',
database: 'mydatabase',
schema: 'public', // Default schema
entities: ['dist/entities/*.entity{.ts,.js}'],
});Master-Slave Replication
TypeORM supports master-slave replication for high availability and load balancing:
const dataSource = new DataSource({
type: 'mysql',
replication: {
master: {
host: 'master-db.example.com',
port: 3306,
username: 'replica',
password: 'replicapassword',
database: 'mydatabase',
},
slaves: [
{
host: 'slave-db1.example.com',
port: 3306,
username: 'replica',
password: 'replicapassword',
database: 'mydatabase',
},
{
host: 'slave-db2.example.com',
port: 3306,
username: 'replica',
password: 'replicapassword',
database: 'mydatabase',
},
],
},
entities: ['dist/entities/*.entity{.ts,.js}'],
});Using Multiple DataSources
Select the appropriate DataSource for operations:
const dataSource1 = await createDataSource(dataSourceOptions1);
const dataSource2 = await createDataSource(dataSourceOptions2);
const userRepo1 = dataSource1.getRepository(User);
const userRepo2 = dataSource2.getRepository(User);
const user1 = await userRepo1.findOne({ where: { id: 1 } });
const user2 = await userRepo2.findOne({ where: { id: 1 } });Cross-DataSource Operations
Perform operations across DataSources using manual transaction management:
async function performCrossDataSourceOperation() {
try {
const queryRunner1 = dataSource1.createQueryRunner();
const queryRunner2 = dataSource2.createQueryRunner();
await queryRunner1.connect();
await queryRunner2.connect();
await queryRunner1.startTransaction();
await queryRunner2.startTransaction();
const data = await queryRunner1.manager.findOne(User, { where: { id: 1 } });
const newUser = new User();
newUser.name = data.name;
await queryRunner2.manager.save(newUser);
await queryRunner1.commitTransaction();
await queryRunner2.commitTransaction();
} catch (error) {
await queryRunner1.rollbackTransaction();
await queryRunner2.rollbackTransaction();
} finally {
await queryRunner1.release();
await queryRunner2.release();
}
}DataSource API
Instantiating a DataSource
Create a DataSource instance during application startup:
import { DataSource } from 'typeorm';
const dataSource = new DataSource({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'mydatabase',
entities: ['dist/entities/*.entity{.ts,.js}'],
migrations: ['dist/migrations/*.js'],
});
await dataSource.initialize();Key Methods and Properties
manager
Returns an EntityManager instance for CRUD operations:
const entityManager = dataSource.manager;
const user = new User();
user.name = 'John Doe';
await entityManager.save(user);getEntityManager()
Obtains a new EntityManager instance:
const em = dataSource.getEntityManager();
const user = await em.findOne(User, { where: { name: 'John Doe' } });getRepository()
Obtains a Repository instance for an entity:
const userRepository = dataSource.getRepository(User);
const users = await userRepository.find();createQueryRunner()
Creates a QueryRunner instance for transactions or complex operations:
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
await queryRunner.manager.save(new User());
await queryRunner.commitTransaction();
} catch (error) {
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}runMigrations()
Runs all pending migrations:
await dataSource.runMigrations();showMigrations()
Displays migration statuses:
const migrations = await dataSource.showMigrations();
console.log(migrations);destroy()
Closes the DataSource, releasing resources:
await dataSource.destroy();Advanced Features
Multiple DataSources
Each DataSource has its own EntityManager and Repository, facilitating database switching.
Replication and Load Balancing
In replication setups, read operations are routed to slaves, and write operations to the master.
Listeners and Subscribers
Register event listeners for database events:
dataSource.on('connect', () => {
console.log('Database connected!');
});



