一、配置基本步骤
-
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 }); } ...
- 4、更多操作见typeorm 官网
四、关于实体类的补充说明
-
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('删除失败'); } }