TypeORM is an ORM
that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms
and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8).
Its goal is to always support the latest JavaScript features and provide additional features
that help you to develop any kind of application that uses databases - from
small applications with a few tables to large scale enterprise applications
with multiple databases.
TypeORM supports both Active Record and Data Mapper patterns,
unlike all other JavaScript ORMs currently in existence,
which means you can write high quality, loosely coupled, scalable,
maintainable applications the most productive way.
TypeORM is highly influenced by other ORMs, such as Hibernate,
Doctrine and Entity Framework.
Some TypeORM features:
- supports both DataMapper and ActiveRecord (your choice)
- entities and columns
- database-specific column types
- entity manager
- repositories and custom repositories
- clean object relational model
- associations (relations)
- eager and lazy relations
- uni-directional, bi-directional and self-referenced relations
- supports multiple inheritance patterns
- cascades
- indices
- transactions
- migrations and automatic migrations generation
- connection pooling
- replication
- using multiple database connections
- working with multiple databases types
- cross-database and cross-schema queries
- elegant-syntax, flexible and powerful QueryBuilder
- left and inner joins
- proper pagination for queries using joins
- query caching
- streaming raw results
- logging
- listeners and subscribers (hooks)
- supports closure table pattern
- schema declaration in models or separate configuration files
- connection configuration in json / xml / yml / env formats
- supports MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js
- supports MongoDB NoSQL database
- works in NodeJS / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms
- TypeScript and JavaScript support
- produced code is performant, flexible, clean and maintainable
- follows all possible best practices
- CLI
And more...
With TypeORM your models look like this:
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
age: number;
}
And your domain logic looks like this:
const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.age = 25;
await repository.save(user);
const allUsers = await repository.find();
const firstUser = await repository.findOne(1); // find by id
const timber = await repository.findOne({ firstName: "Timber", lastName: "Saw" });
await repository.remove(timber);
Alternatively, if you prefer to use the ActiveRecord implementation, you can use it as well:
import {Entity, PrimaryGeneratedColumn, Column, BaseEntity} from "typeorm";
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
age: number;
}
And your domain logic will look this way:
const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.age = 25;
await user.save();
const allUsers = await User.find();
const firstUser = await User.findOne(1);
const timber = await User.findOne({ firstName: "Timber", lastName: "Saw" });
await timber.remove();
Installation
Install the npm package:
npm install typeorm --save
You need to install reflect-metadata shim:
npm install reflect-metadata --save
and import it somewhere in the global place of your app (for example in app.ts):
import "reflect-metadata";
You may need to install node typings:
npm install @types/node --save
Install a database driver:
for MySQL or MariaDB
npm install mysql --save (you can install mysql2 instead as well)
for PostgreSQL or CockroachDB
npm install pg --save
for SQLite
npm install sqlite3 --save
for Microsoft SQL Server
npm install mssql --save
for sql.js
npm install sql.js --save
for Oracle
npm install oracledb --save
To make the Oracle driver work, you need to follow the installation instructions from
their site.
for SAP Hana
npm config set @sap:registry https://npm.sap.com
npm i @sap/hana-client
npm i hdb-pool
for MongoDB (experimental)
npm install mongodb --save
for NativeScript, react-native and Cordova
Check documentation of supported platforms
Install only one of them, depending on which database you use.
TypeScript configuration
Also, make sure you are using TypeScript version 3.3 or higher,
and you have enabled the following settings in tsconfig.json:
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
You may also need to enable es6 in the lib section of compiler options, or install es6-shim from @types.
Quick Start
The quickest way to get started with TypeORM is to use its CLI commands to generate a starter project.
Quick start works only if you are using TypeORM in a NodeJS application.
If you are using other platforms, proceed to the step-by-step guide.
First, install TypeORM globally:
npm install typeorm -g
Then go to the directory where you want to create a new project and run the command:
typeorm init --name MyProject --database mysql
Where name is the name of your project and database is the database you'll use.
Database can be one of the following values: mysql, mariadb, postgres, cockroachdb, sqlite, mssql, oracle, mongodb,
cordova, react-native, expo, nativescript.
This command will generate a new project in the MyProject directory with the following files:
MyProject
├── src // place of your TypeScript code
│ ├── entity // place where your entities (database models) are stored
│ │ └── User.ts // sample entity
│ ├── migration // place where your migrations are stored
│ └── index.ts // start point of your application
├── .gitignore // standard gitignore file
├── ormconfig.json // ORM and database connection configuration
├── package.json // node module dependencies
├── README.md // simple readme file
└── tsconfig.json // TypeScript compiler options
You can also run typeorm init on an existing node project, but be careful - it may override some files you already have.
The next step is to install new project dependencies:
cd MyProject
npm install
While installation is in progress, edit the ormconfig.json file and put your own database connection configuration options in there:
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "test",
"password": "test",
"database": "test",
"synchronize": true,
"logging": false,
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
]
}
Particularly, most of the time you'll only need to configure
host, username, password, database and maybe port options.
Once you finish with configuration and all node modules are installed, you can run your application:
npm start
That's it, your application should successfully run and insert a new user into the database.
You can continue to work with this project and integrate other modules you need and start
creating more entities.
You can generate an even more advanced project with express installed by running
typeorm init --name MyProject --database mysql --express command.
Step-by-Step Guide
What are you expecting from ORM?
First of all, you are expecting it will create database tables for you
and find / insert / update / delete your data without the pain of
having to write lots of hardly maintainable SQL queries.
This guide will show you how to setup TypeORM from scratch and make it do what you are expecting from an ORM.
Create a model
Working with a database starts from creating tables.
How do you tell TypeORM to create a database table?
The answer is - through the models.
Your models in your app are your database tables.
For example, you have a Photo model:
export class Photo {
id: number;
name: string;
description: string;
filename: string;
views: number;
isPublished: boolean;
}
And you want to store photos in your database.
To store things in the database, first you need a database table,
and database tables are created from your models.
Not all models, but only those you define as entities.
Create an entity
Entity is your model decorated by an @Entity decorator.
A database table will be created for such models.
You work with entities everywhere with TypeORM.
You can load/insert/update/remove and perform other operations with them.
Let's make our Photo model as an entity:
import {Entity} from "typeorm";
@Entity()
export class Photo {
id: number;
name: string;
description: string;
filename: string;
views: number;
isPublished: boolean;
}
Now, a database table will be created for the Photo entity and we'll be able to work with it anywhere in our app.
We have created a database table, however what table can exist without columns?
Let's create a few columns in our database table.
Adding table columns
To add database columns, you simply need to decorate an entity's properties you want to make into a column
with a @Column decorator.
import {Entity, Column} from "typeorm";
@Entity()
export class Photo {
@Column()
id: number;
@Column()
name: string;
@Column()
description: string;
@Column()
filename: string;
@Column()
views: number;
@Column()
isPublished: boolean;
}
Now id, name, description, filename, views and isPublished columns will be added to the photo table.
Column types in the database are inferred from the property types you used, e.g.
number will be converted into integer, string into varchar, boolean into bool, etc.
But you can use any column type your database supports by explicitly specifying a column type into the @Column decorator.
We generated a database table with columns, but there is one thing left.
Each database table must have a column with a primary key.
Creating a primary column
Each entity must have at least one primary key column.
This is a requirement and you can't avoid it.
To make a column a primary key, you need to use @PrimaryColumn decorator.
import {Entity, Column, PrimaryColumn} from "typeorm";
@Entity()
export class Photo {
@PrimaryColumn()
id: number;
@Column()
name: string;
@Column()
description: string;
@Column()
filename: string;
@Column()
views: number;
@Column()
isPublished: boolean;
}
Creating an auto generated column
Now, let's say you want your id column to be auto-generated (this is known as auto-increment / sequence / serial / generated identity column).
To do that, you need to change the @PrimaryColumn decorator to a @PrimaryGeneratedColumn decorator:
import {Entity, Column, PrimaryGeneratedColumn} from "typeorm";
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
description: string;
@Column()
filename: string;
@Column()
views: number;
@Column()
isPublished: boolean;
}
Column data types