安装依赖

  1. yarn add @nestjs/typeorm typeorm mysql

配置mysql

  1. // mysql
  2. import { TypeOrmModule } from "@nestjs/typeorm";
  3. // 模块
  4. import { MysqldemoModule } from "./mysqldemo/mysqldemo.module";
  5. @Module({
  6. // 连接mongodb数据库
  7. imports: [
  8. MysqldemoModule, // 模块
  9. TypeOrmModule.forRoot({
  10. type:"mysql",
  11. host:"localhost",
  12. port:3306,
  13. username:"root",
  14. password:'12345678',
  15. database:"test",
  16. entities:[__dirname+'/**/*.entity{.ts,.js}'], // 实体
  17. synchronize:true // 同步?
  18. })
  19. ],
  20. })

定义实体

  1. import { Entity ,PrimaryGeneratedColumn , Column} from 'typeorm';
  2. @Entity()
  3. export class Mysql{
  4. // 自增主键
  5. @PrimaryGeneratedColumn()
  6. id:number;
  7. // Column : 如果数据库没有自动创建
  8. @Column({length:255})
  9. name:string;
  10. @Column('int')
  11. age:number
  12. }

配置模块

  1. import { Module } from '@nestjs/common';
  2. // 配置模块
  3. import { TypeOrmModule } from '@nestjs/typeorm'
  4. // 实例
  5. import { Mysql } from "../entity/mysql.entity";
  6. import { MysqldemoController } from "./mysqldemo.controller";
  7. import { MysqldemoService } from './mysqldemo.service';
  8. @Module({
  9. controllers:[MysqldemoController],
  10. imports:[
  11. TypeOrmModule.forFeature([Mysql])
  12. ],
  13. providers: [MysqldemoService]
  14. })
  15. export class MysqldemoModule {}

接口

  1. import { Controller, Get } from '@nestjs/common';
  2. import { MysqldemoService } from "./mysqldemo.service";
  3. @Controller('mysqldemo')
  4. export class MysqldemoController {
  5. constructor(
  6. private readonly mysqldemoService:MysqldemoService
  7. ){}
  8. @Get()
  9. index(){
  10. return this.mysqldemoService.findAll()
  11. }
  12. }

服务

  1. import { Injectable } from '@nestjs/common';
  2. import { InjectRepository } from "@nestjs/typeorm";
  3. import { Repository } from "typeorm";
  4. import { Mysql } from '../entity/mysql.entity';
  5. @Injectable()
  6. export class MysqldemoService {
  7. constructor(
  8. // 把实例 赋值给变量
  9. @InjectRepository(Mysql)
  10. private readonly mysqlRepository:Repository<Mysql>
  11. ){}
  12. findAll(){
  13. return this.mysqlRepository.find()
  14. }
  15. }