Releases: scalio/typeorm
0.2.18
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 / 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 installmysql2
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
Install only one of them, depending on which database you use.
To make the Oracle driver work, you need to follow the installation instructions from
their site. -
for MongoDB (experimental)
npm install mongodb --save
-
for NativeScript, react-native and Cordova
-
TypeScript configuration
Also, make sure you are using TypeScript compiler version 3.3 or greater,
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...