Skip to content

TypeORM

安装

bash
npm i @nestjs/typeorm typeorm mysql2 -S

pnpm i @nestjsx/crud-typeorm -S

pnpm i @nestjsx/crud -S

找到模块文件

  • 设置全局

  • 找到 entity 下面的所有实体类

ts
import { Global, Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import User from "./model/User.entity";
import { UserController } from "./controller/user.controller";
import { UserService } from "./service/user.service";
@Global()
@Module({
  imports: [
    TypeOrmModule.forRoot({
      // 数据库类型
      type: "mysql",
      // 数据库地址
      host: "localhost",
      // 数据库端口号
      port: 3306,
      // 用户名
      username: "root",
      // 密码
      password: "123456",
      // 数据库名称
      database: "testnest1",
      // 指定模型层
      entities:['./**/entity/*.ts']
      // 开启打印生成sql语句
      logging: false,
      // 同步数据库
      synchronize: true,
      migrations: [],
      // 订阅
      subscribers: [],
      // 连接池
      connectorPackage: 'mysql2'
    }),
    TypeOrmModule.forFeature([User]), //操作模型层数据,要是多个类似User,List
  ],
  controllers: [UserController],
  providers: [UserService],
})
export class CoreModule {}

创建实体类

基础版

数据库中的表是根据实体类来创建的,所以需要创建实体类。看下生成的默认实体类 User.ts

ts
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  age: number;
}

中级版

ts
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({
    type: "varchar",
    length: 20,
    name: "first_name",
    comment: "姓氏",
  })
  firstName: string;

  @Column({
    type: "varchar",
    name: "last_name",
    length: 20,
    comment: "名字",
  })
  lastName: string;

  @Column({
    type: "int",
    comment: "年龄",
  })
  age: number;

  @Column({
    type: "double",
    comment: "num",
  })
  num: number;

  @Column({
    type: "text",
    comment: "text",
  })
  text: string;
}

注意

  1. @Entity: 标识这是一个实体类

  2. @PrimaryGeneratedColumn:标识这是一个主键,并且自增

  3. @Column 标识这是一个字段,并且可以自定义字段的类型,长度,名称,注释等等

@Colum 中可以自定义字段的类型,但是需要注意的是,如果是 mysql 数据库,那么 type 的值需要是 mysql 数据库中的数据类型

比如 varcharintdoubletext 等。按照这个实体重新生成 user

通过对实体的定义就可以新建表以及确定数据的类型

写 Service

ts
import { TypeOrmCrudService } from "@nestjsx/crud-typeorm";
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import UserEntity from "../model/User.entity";

@Injectable()
export class UserService extends TypeOrmCrudService<UserEntity> {
  constructor(@InjectRepository(UserEntity) repo) {
    super(repo);
  }
  async createUser() {
    const user = new UserEntity();
    user.username = "abdc";
    return await this.repo.save(user);
  }
}

注意

  • save:新增或者修改 Entity,如果传入了 id 会先 select 再决定修改还新增
  • update:直接修改 Entity,不会先 select
  • insert:直接插入 Entity
  • delete:删除 Entity,通过 id
  • remove:删除 Entity,通过对象
  • find:查找多条记录,可以指定 where、order by 等条件
  • findBy:查找多条记录,第二个参数直接指定 where 条件,更简便一点
  • findAndCount:查找多条记录,并返回总数量
  • findByAndCount:根据条件查找多条记录,并返回总数量
  • findOne:查找单条记录,可以指定 where、order by 等条件
  • findOneBy:查找单条记录,第二个参数直接指定 where 条件,更简便一点
  • findOneOrFail:查找失败会抛 EntityNotFoundError 的异常
  • query:直接执行 sql 语句
  • createQueryBuilder:创建复杂 sql 语句,比如 join 多个 Entity 的查询
  • transaction:包裹一层事务的 sql
  • getRepository:拿到对单个 Entity 操作的类,方法同 EntityManager

写 Controller

ts
import {
  Body,
  Controller,
  Delete,
  Get,
  Inject,
  Param,
  Patch,
  Post,
} from "@nestjs/common";
import { UserService } from "../service/user.service";

@Controller("users")
export class UserController {
  constructor() {}

  @Inject()
  private UserService: UserService;

  @Post()
  async create(): Promise<string> {
    await this.UserService.createUser();
    return "User created";
  }
}