TypeOrm
TypeOrm是TypeScript中最成熟的对象关系映射器(ORM),因为它是用TypeScript编写的,所以可以很好地与Nest框架集成
安装依赖:
1
| npm install --save @nestjs/typeorm typeorm mysql2
|
引入TypeOrm
在app.module.ts注册:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { TestModule } from './test/test.module';
@Module({ imports: [ TypeOrmModule.forRoot({ type: 'mysql', username: 'root', password: 'cherry114514', host: 'localhost', port: 3306, database: 'nest', synchronize: true, retryDelay: 500, retryAttempts: 10, autoLoadEntities: true, }), TestModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
|
在Entities中定义实体:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity() export class Test { @PrimaryGeneratedColumn() id: number;
@Column() name: string;
@Column() password: string;
@Column() age: number; }
|
在对应的Module中关联实体:
1 2 3 4 5 6 7 8 9 10 11 12 13
| import { Module } from '@nestjs/common'; import { TestService } from './test.service'; import { TestController } from './test.controller'; import { Test } from '@nestjs/testing'; import { TypeOrmModule } from '@nestjs/typeorm';
@Module({ imports: [TypeOrmModule.forFeature([Test])], controllers: [TestController], providers: [TestService], }) export class TestModule {}
|