TypeORM
TypeORM is the most mature object relation mapper (ORM) in the existing community of node.js. This article describes how to use TypeORM in Midway.
This module is a new version from v3.4.0. The module name has changed and the history is partially compatible. For more information about how to query historical documents, see here.
Related information:
| Description | |
|---|---|
| Can be used for standard projects | ✅ |
| Can be used for Serverless | ✅ |
| Can be used for integration | ✅ |
| Contains independent main framework | ❌ |
| Contains independent logs | ❌ |
The difference with the old writing
The old module is @midwayjs/orm and the new module is @midwayjs/typeorm. The differences are as follows:
-
- Different package names
-
- Adjust some configurations in
src/config.default
- The key in the 2.1 configuration file is different (orm => typeorm)
- The 2.2 is modified to the form of a data source to
typeorm.dataSource - The path to 2.3 an entity model class or an entity model class needs to be declared in the
entitiesfield of the data source. - 2.4 Subscriber need to be declared in the
subscribersfield of the data source
- Adjust some configurations in
- 3, no longer use the
EntityModeldecorator, directly use the ability provided by the typeorm
Installation Components
Install typeorm components to provide database ORM capability.
$ npm i @midwayjs/typeorm@3 typeorm --save
Or reinstall the following dependencies in package.json.
{
"dependencies": {
"@midwayjs/typeorm": "^3.0.0",
"typeorm": "~0.3.0 ",
// ...
},
"devDependencies": {
// ...
}
}
Introducing components
Introducing orm components in src/configuration.ts, an example is as follows.
// configuration.ts
import { Configuration } from '@midwayjs/core';
import * as orm from '@midwayjs/typeorm';
import { join } from 'path';
@Configuration({
imports: [
// ...
orm, // enable typeorm component
],
importConfigs: [
join(__dirname, './config')
]
})
export class MainConfiguration {
}
Install database Driver
The commonly used database drivers are as follows. Select the database type to install the corresponding connection:
# for MySQL or MariaDB, you can also use mysql2 instead
npm install mysql --save
npm install mysql2 --save
# 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
# for MongoDB(experimental)
npm install mongodb --save
- Oracle driver is special, you need to view the documentation
- typeorm link mongodb is not recommended, please use mongoose components
Simple directory structure
We take a simple project as an example, please refer to other structures.
MyProject
├── src // TS root directory
│ ├── config
│ │ └── config.default.ts // Application Profile
│ ├── entity // entity (database Model) directory
│ │ └── photo.entity.ts // entity file
│ │ └── photoMetadata.ts
│ ├── configuration.ts // Midway configuration file
│ └── service // Other service directory
├── .gitignore
├── package.json
├── README.md
└── tsconfig.json
Here, our database entities are mainly located in the entity directory (non-mandatory). This is a simple convention.
Getting Started
Next, we will take mysql as an example.
1. Create Model
We associate with the database through the model. The model in the application is the database table. In the TypeORM, the model is bound to the entity. Each Entity file is a Model and an Entity.
In the example, you need an entity. Let's take photo as an example. Create an entity directory and add the entity file photo.entity.ts to the entity directory. A simple entity is as follows.
// entity/photo.entity.ts
export class Photo {
id: number;
name: string;
description: string;
filename: string;
views: number;
isPublished: boolean;
}
Note that each attribute of the entity file here is actually one-to-one corresponding to the database table. Based on the existing database table, we add content up.
2. Define the entity model
Entity is used to define an entity model class.
// entity/photo.entity.ts
import { Entity } from 'typeorm';
@Entity('photo')
export class Photo {
id: number;
name: string;
description: string;
filename: string;
views: number;
isPublished: boolean;
}
If the table name is different from the current entity name, you can specify it in the parameter.
// entity/photo.entity.ts
import { Entity } from 'typeorm';
@Entity('photo_table_name')
export class Photo {
id: number;
name: string;
description: string;
filename: string;
views: number;
isPublished: boolean;
}
These entity columns can also be generated using typeorm_generator tools.
3. Add database columns
The properties are modified by the @Column decorator provided by the typeorm, each corresponding to a column.
// entity/photo.entity.ts
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;
}
The id, name, description, filename, views, isPublished columns are added to the photo table. The column types in the database are inferred according to the attribute types you use, for example, number will be converted to integers, strings will be converted to varchar, boolean values will be converted to bool, and so on. However, you can use any column type supported by the database by explicitly specifying the column type in 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.
Database columns include more column options (ColumnOptions), such as modifying column names, specifying column types, and column lengths. For more options, see the [official documentation](https://github.com/typeorm/typeorm/blob/master/docs/zh_CN/entities.md#%E5%88% 97% E9%80% 89% E9%A1%B9).
4. Create a primary key column
Each entity must have at least one primary key column. To make a column a primary key, you need to use the @PrimaryColumn decorator.
// entity/photo.entity.ts
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;
}