Database(TypeORM)
TypeORM 是 node.js
现有社区最成熟的对象关系映射器(ORM
)。Midway 和 TypeORM 搭配,使开发更简单。
安装组件
安装 orm 组件,提供数据库 ORM 能力。
npm i @midwayjs/orm@2 typeorm --save
info
当前已升级为 2.x 版本,变化见这里。
引入组件
在 src/configuration.ts
引入 orm 组件,示例如下。
// configuration.ts
import { Configuration } from '@midwayjs/decorator';
import * as orm from '@midwayjs/orm';
import { join } from 'path';
@Configuration({
imports: [
orm, // 加载 orm 组件
],
importConfigs: [join(__dirname, './config')],
})
export class ContainerConfiguratin {}
安装数据库 Driver
常用数据库驱动如下,选择你对应连接的数据库类型安装:
# for MySQL or MariaDB,也可以使用 mysql2 替代
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
info
To make the** Oracle driver work**, you need to follow the installation instructions from their site.
简单的目录结构
我们以一个简单的项目举例,其他结构请自行参考。
MyProject
├── src // TS 根目录
│ ├── config
│ │ └── config.default.ts // 应用配置文件
│ ├── entity // 实体(数据库 Model) 目录
│ │ └── photo.ts // 实体文件
│ │ └── photoMetadata.ts
│ ├── configuration.ts // Midway 配置文件
│ └── service // 其他的服务目录
├── .gitignore
├── package.json
├── README.md
└── tsconfig.json
在这里,我们的数据库实体主要放在 entity
目录(非强制),这只是一个简单的约定。
入门
下面,我们将以 mysql 举例。
1、创建 Model
我们通过模型和数据库关联,在应用中的模型就是数据库表,在 TypeORM 中,模型是和实体绑定的,每一个实体(Entity) 文件,即是 Model,也是实体(Entity)。
在示例中,需要一个实体,我们这里拿 photo
举例。新建 entity 目录,在其中添加实体文件 photo.ts
,一个简单的实体如下。
// entity/photo.ts
export class Photo {
id: number;
name: string;
description: string;
filename: string;
views: number;
isPublished: boolean;
}
要注意,这里的实体文件的每一个属性,其实是和数据库表一一对应的,基于现有的数 据库表,我们往上添加内容。
2、添加实体模型装饰器
我们使用 EntityModel
来定义一个实体模型类。
// entity/photo.ts
import { EntityModel } from '@midwayjs/orm';
@EntityModel('photo')
export class Photo {
id: number;
name: string;
description: string;
filename: string;
views: number;
isPublished: boolean;
}
attention
注意,这里的 EntityModel 是 midway 做了封装的特殊装饰器,为了和 midway 更好的结合使用。请不要直接使用 typeorm 中的 Entity。
如果表名和当前的实体名不同,可以在参数中指定。
// entity/photo.ts
import { EntityModel } from '@midwayjs/orm';
@EntityModel('photo_table_name')
export class Photo {
id: number;
name: string;
description: string;
filename: string;
views: number;
isPublished: boolean;
}
这些实体列也可以使用 typeorm_generator 工具生成。