nestjs对mysql数据库的基本操作

一、配置基本步骤

  • 1、安装基本的包

    npm install --save @nestjs/typeorm typeorm mysql
    
  • 2、在项目的根目录下创建一个ormconfig.josn文件

    {
    	type: 'mysql',
    	host: 'localhost',
    	port: 3306,
    	username: 'root',
    	password: '123456',
    	database: 'test',
    	entities: [resolve(`./**/*.entity.ts`)],
    	migrations: ['migration/*.ts'],
    	timezone: 'UTC',
    	charset: 'utf8mb4',
    	multipleStatements: true,
    	dropSchema: false,
    	synchronize: true, // 是否自动将实体类同步到数据库
    	logging: true,
    }
    
  • 3、在app.module.ts文件中使用数据库的配置

    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { CatModule } from './cat/cat.module';
    // 引入数据库的及配置文件
    import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
    
    @Module({
      imports: [
        CatModule,
        TypeOrmModule.forRoot(), // 数据库的
      ],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}
    

二、在cat的模块构建表

  • 1、创建一个cat.entity.ts的实体类

    import { Entity, PrimaryGeneratedColumn, Column, Timestamp } from 'typeorm';
    
    @Entity()
    export class Cat {
      // 会以类名来创建表,如果是驼峰命名的,生成的表名是下划线区分
      @PrimaryGeneratedColumn({ comment: '主键id' })
      id: number;
    
      @Column({ length: 100, comment: 'uuid', generated: 'uuid' })
      uuid: string;
    
      @Column({ length: 50, comment: '名字', unique: true })
      name: string;
    
      @Column({ comment: '年龄' })
      age: number;
    
      @Column({
        type: 'varchar',
        length: 30,
        comment: '颜色',
        nullable: true,
        // default: null,
      })
      color: string;
    
      @Column({ type: 'timestamp', default: () => 'current_timestamp' })
      createAt: Timestamp;
    
      @Column({
        type: 'timestamp',
        onUpdate: 'current_timestamp',
        default: () => 'current_timestamp',
      })
      updateAt: Timestamp;
    }
    
  • 2、会自动生成表

  • 3、查看表结构

    mysql> desc cat;
    +----------+--------------+------+-----+-------------------+-----------------------------+
    | Field    | Type         | Null | Key | Default           | Extra                       |
    +----------+--------------+------+-----+-------------------+-----------------------------+
    | id       | int(11)      | NO   | PRI | NULL              | auto_increment              |
    | uuid     | varchar(100) | NO   |     | NULL              |                             |
    | name     | varchar(50)  | NO   | UNI | NULL              |                             |
    | age      | int(11)      | NO   |     | NULL              |                             |
    | color    | varchar(30)  | YES  |     | NULL              |                             |
    | createAt | timestamp    | NO   |     | CURRENT_TIMESTAMP |                             |
    | updateAt | timestamp    | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
    +----------+--------------+------+-----+-------------------+-----------------------------+
    7 rows in set (0.00 sec)
    
    mysql>
    
  • 4、在需要使用的cat.module.ts中注册实体类

    import { TypeOrmModule } from '@nestjs/typeorm';
    import { CatEntity } from './cat.entity';
    
    @Module({
      imports: [TypeOrmModule.forFeature([CatEntity])],
      controllers: [CatController],
      providers: [CatService],
    })
    export class CatModule {}
    
  • 5、在服务层@InjectRepository() 修饰器向 CatService 注入 CatRepository

    import { Repository } from 'typeorm';
    import { CatEntity } from './cat.entity';
    import { CreateCatDto } from './dto/create.cat.dto';
    
    @Injectable()
    export class CatService {
      constructor(
        @InjectRepository(CatEntity)
        private readonly catRepository: Repository<CatEntity>,
      ) {}
    }
    

三、基本语句的使用

  • 1、新增数据

    ...
    // 创建的方法
    async create(createCatDto: CreateCatDto): Promise<CatEntity> {
      return await this.catRepository.save(createCatDto);
    }
    ...
    
  • 2、查询全部数据

    ...
    // 查询全部数据
    async findAll(): Promise<CatEntity[]> {
      return await this.catRepository.find();
    }
    ...
    
  • 3、查询一条数据

    ...
    // 查找一条数据
    async findOne(id: number): Promise<CatEntity> {
      return await this.catRepository.findOne({ id });
    }
    ...
    

四、关于实体类的补充说明

  • 1、可以直接在app.module.ts中添加全部的实体类,那么在具体的上面就不需要添加实体类了

    import { CatEntity } from './cat/cat.entity'
    
    const ENTITIES = [
      CatEntity,
    ]
    @Module({
      imports: [
        CatModule,
        TypeOrmModule.forRoot(config.orm as TypeOrmModuleOptions),
        TypeOrmModule.forFeature([...ENTITIES]),
      ],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}
    

五、关于typeorm知识点的补充

  • 1、使用原生语句

    ...
    async findAll(): Promise<CatEntity[]> {
      return await this.catRepository.query('select * from cat');
    }
    ...
    
  • 2、使用createQueryBuilder

    // 查询全部数据
    async findAll(): Promise<CatEntity[]> {
      return await this.catRepository
        .createQueryBuilder('cat') // 查询表名
        .offset(1) // 从多少条开始
        .limit(2) // 查询2条数据
        .orderBy('age', 'DESC') // 排序
        .getMany(); // 返回多条数据
    }
    
  • 3、typeorm主要的方法

    • save
    • remove
    • insert
    • update
    • delete
    • count
    • find
    • findAndCount
    • findByIds
    • findOne
    • findOneOrFail
    • query
    • increment
    • decrement
  • 4、个人更加推荐使用createQueryBuilder或者query进行原生sql查询,上面的方法不能链式调用,很受限

六、使用typeorm开启数据库事务

  • 1、删除一个关联表的数据

    async deleteById(id: number): Promise<string> {
      /**
       * 创建连接并开启事务
       */
      const connection = getConnection();
      const queryRunner = connection.createQueryRunner();
      await queryRunner.connect();
      await queryRunner.startTransaction();
      try {
        await queryRunner.manager.query('delete from users where id = ?', [id]);
        await queryRunner.manager.query(
          'delete from users_extend where userId = ?',
          [id],
        );
        await queryRunner.commitTransaction();
        return '删除成功';
      } catch (e) {
        await queryRunner.rollbackTransaction();
        throw new BadRequestException('删除失败');
      }
    }
    
NestJS是一个基于TypeScript的开源Web框架,它专注于构建高效、模块化的Node.js服务器。达梦数据库(DM),原名为Informix DM,是一款高性能的关系型数据库管理系统,由中国东方通用软件技术有限公司开发。 在NestJS应用中集成达梦数据库,你可以按照以下步骤操作: 1. **安装依赖**:首先需要通过npm或yarn安装`nestjs-typeorm`,因为它提供了NestJS和TypeORM之间的整合支持,然后单独安装`typeorm`和对应的达梦驱动包(如`typeorm-dm`)。 ```bash npm install @nestjs/typeorm typeorm dm-driver ``` 2. **配置**:在项目中创建一个ormconfig.json文件,添加达梦的相关配置,包括数据库地址、用户名、密码等。 ```json { "type": "mysql", "host": "your_host", "port": 5000, "username": "your_username", "password": "your_password", "database": "your_database", "entities": ["src/**/*.entity.ts"], "logging": false, " synchronize": true } ``` 注意将`type`改为`dm`。 3. **创建实体**:在NestJS项目的entity目录下,创建包含达梦特性的数据模型类(Entity)。 4. **注入服务**:在服务或控制器中,通过TypeORM提供的`@InjectRepository()`注解注入数据库仓库。 ```typescript import { Injectable } from '@nestjs/common'; import { Repository } from 'typeorm'; import { YourEntity } from './your-entity.entity'; @Injectable() export class YourService { constructor(private readonly yourRepo: Repository<YourEntity>) {} } ``` 5. **执行查询**:现在可以使用`yourRepo`执行CRUD操作了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值