Nestjs联合Typeorm操作Mysql数据库

2023-12-10 16:12

本文主要是介绍Nestjs联合Typeorm操作Mysql数据库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

创建项目

// 安装脚手架(只需要安装一次,因为这个是全局的)
npm i -g @nestjs/cli
// 创建项目
nest new project-name
// (该过程有个选择包管理工具的,我选的yarn)

启动项目

yarn run start:dev
// 可以在浏览器访问localhost:3000  输出helloWorld

安装typeorm,mysql2和@nestjs/typeorm

// 安装依赖
yarn add --save @nestjs/typeorm typeorm mysql2
// @nestjs/typeorm这个本人运行上面命令一直安装不上,只好单独安装一下就成功了(yarn add @nestjs/typeorm)

创建实体模块

nest g res user2

连接数据库(app.module.ts)

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './user/user.module';
import { User2Module } from './user2/user2.module';
@Module({imports: [TypeOrmModule.forRoot({type: 'mysql',host: 'localhost',port: 3306,username: 'root',password: 'admin',database: 'shop',autoLoadEntities: true,synchronize: true,}),UserModule,User2Module,],controllers: [AppController],providers: [AppService],
})
export class AppModule {}

上面将框架搭建完成了,后面都是对代码的修改

/src/user2/entities/user2.entity.ts

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';@Entity()
export class User2 {@PrimaryGeneratedColumn()id: number;@Column()firstName: string;@Column()lastName: string;@Column({ default: true })isActive: boolean;
}

/src/user2/user2.module.ts

import { Module } from '@nestjs/common';
import { User2Service } from './user2.service';
import { User2Controller } from './user2.controller';
// 引入实体
import { User2 } from './entities/user2.entity';
// 引入orm框架
import {TypeOrmModule} from '@nestjs/typeorm'
@Module({imports:[TypeOrmModule.forFeature([User2])],controllers: [User2Controller],providers: [User2Service],
})
export class User2Module {}

到这一步,运行项目会发现数据库多出来一张user2的表,表字段和user2.entity.ts一一对应
接下来三个文件内都是逻辑代码

/src/user2/dto/create-user2.dto.ts

// 这里在添加数据用上了
export class CreateUser2Dto {firstName: string;lastName: string;isActive: boolean;
}

/src/user2/user2.controller.ts

import {Controller,Get,Post,Body,Patch,Param,Delete,Query,DefaultValuePipe,ParseIntPipe,
} from '@nestjs/common';
import { User2Service } from './user2.service';
import { CreateUser2Dto } from './dto/create-user2.dto';
import { UpdateUser2Dto } from './dto/update-user2.dto';@Controller('user2')
export class User2Controller {constructor(private readonly user2Service: User2Service) {}@Post() // 这里添加数据使用了apifox,调至post接口,Body-json类型,将添加的字段依次输入即可,直接发请求 http://localhost:3000/user2async create(@Body() createUser2Dto: CreateUser2Dto) {const res = await this.user2Service.create(createUser2Dto);if (res.generatedMaps.length > 0) {return {success: '添加成功',};} else {error: '添加失败';}return this.user2Service.create(createUser2Dto);}// 查询所有@Get()findAll(@Query('current', new DefaultValuePipe(1), ParseIntPipe) current: number, // 页数,默认值为1,int类型@Query('pagesize', new DefaultValuePipe(15), ParseIntPipe) pagesize: number, // 每页条数,默认值15) {// 传入当前页数,number类型的return this.user2Service.findAll(current, pagesize);}// 查询单条信息@Get(':id')findOne(@Param('id', ParseIntPipe) id: number) {// 将id类型转换为int类型限制为number类型return this.user2Service.findOne(+id);}// 更新(修改数据) 这里修改数据使用了apifox,调至post接口,Body-json类型,将添加的字段依次输入即可,直接发请求 http://localhost:3000/user2/3@Patch(':id')async update(@Param('id') id: string,@Body() updateUser2Dto: UpdateUser2Dto,) {const user = await this.user2Service.findOne(+id);if (user === null) {return {error: '没有此用户,暂时无法修改',};}const res = await this.user2Service.update(+id, updateUser2Dto);if (res.affected > 0) {return {success: '修改成功',};} else {error: '修改失败';}}// 根据id删除单个用户@Delete(':id')async remove(@Param('id') id: number) {// 先查询到这个用户(这里直接调用根据id查询用户的方法)const user = await this.user2Service.findOne(id); // 在findOne这个方法里面的findOne是使用了promise,因此这里需要异步一下if (user === null) {return { error: '删除的用户不存在' };}const res = this.user2Service.remove(+id);if ((await res).affected > 0) {return {success: '删除成功',};} else {error: '删除失败';}}
}

src/user2/user2.service.ts

import { Injectable } from '@nestjs/common';
import { CreateUser2Dto } from './dto/create-user2.dto';
import { UpdateUser2Dto } from './dto/update-user2.dto';
import { InjectRepository } from '@nestjs/typeorm';
// 1.导入实体
import { User2 } from './entities/user2.entity';
// 2.导入依赖注入
import { Repository } from 'typeorm';
@Injectable()
export class User2Service {// 3.需要对数据库进行操作,这里需要进行依赖注入constructor(@InjectRepository(User2)private user2Repoitory: Repository<User2>,) {}// 新增数据(这里需要用到dto层进行逻辑处理)create(createUser2Dto: CreateUser2Dto) {return this.user2Repoitory.insert(createUser2Dto);}// 查询数据findAll(current = 1, pagesize = 15) {// 查询所有的逻辑代码()(访问localhost:3000/user2)// return this.user2Repoitory.findAndCount();// 分页查询的代码return this.user2Repoitory.findAndCount({skip: (current - 1) * pagesize, // 跳过多少页take: pagesize, // 当前页数});}// 根据id查询findOne(id: number) {// 根据id查询用户信息// return this.user2Repoitory.findOneBy({ id });// 也可以使用findone查询,这个查询毕竟灵活return this.user2Repoitory.findOne({ where: { id } }); // 里面放查询条件}// 更新(修改数据)update(id: number, updateUser2Dto: UpdateUser2Dto) {// 根据id修改数据return this.user2Repoitory.update(id,updateUser2Dto);}// 根据id删除用户remove(id: number) {return this.user2Repoitory.delete(id);}
}

这篇关于Nestjs联合Typeorm操作Mysql数据库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/477600

相关文章

Mysql数据库聚簇索引与非聚簇索引举例详解

《Mysql数据库聚簇索引与非聚簇索引举例详解》在MySQL中聚簇索引和非聚簇索引是两种常见的索引结构,它们的主要区别在于数据的存储方式和索引的组织方式,:本文主要介绍Mysql数据库聚簇索引与非... 目录前言一、核心概念与本质区别二、聚簇索引(Clustered Index)1. 实现原理(以 Inno

sqlserver、mysql、oracle、pgsql、sqlite五大关系数据库的对象名称和转义字符

《sqlserver、mysql、oracle、pgsql、sqlite五大关系数据库的对象名称和转义字符》:本文主要介绍sqlserver、mysql、oracle、pgsql、sqlite五大... 目录一、转义符1.1 oracle1.2 sqlserver1.3 PostgreSQL1.4 SQLi

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

深入理解Mysql OnlineDDL的算法

《深入理解MysqlOnlineDDL的算法》本文主要介绍了讲解MysqlOnlineDDL的算法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小... 目录一、Online DDL 是什么?二、Online DDL 的三种主要算法2.1COPY(复制法)

mysql8.0.43使用InnoDB Cluster配置主从复制

《mysql8.0.43使用InnoDBCluster配置主从复制》本文主要介绍了mysql8.0.43使用InnoDBCluster配置主从复制,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录1、配置Hosts解析(所有服务器都要执行)2、安装mysql shell(所有服务器都要执行)3、

k8s中实现mysql主备过程详解

《k8s中实现mysql主备过程详解》文章讲解了在K8s中使用StatefulSet部署MySQL主备架构,包含NFS安装、storageClass配置、MySQL部署及同步检查步骤,确保主备数据一致... 目录一、k8s中实现mysql主备1.1 环境信息1.2 部署nfs-provisioner1.2.

MySQL中VARCHAR和TEXT的区别小结

《MySQL中VARCHAR和TEXT的区别小结》MySQL中VARCHAR和TEXT用于存储字符串,VARCHAR可变长度存储在行内,适合短文本;TEXT存储在溢出页,适合大文本,下面就来具体的了解... 目录一、VARCHAR 和 TEXT 基本介绍1. VARCHAR2. TEXT二、VARCHAR

MySQL中C接口的实现

《MySQL中C接口的实现》本节内容介绍使用C/C++访问数据库,包括对数据库的增删查改操作,主要是学习一些接口的调用,具有一定的参考价值,感兴趣的可以了解一下... 目录准备mysql库使用mysql库编译文件官方API文档对象的创建和关闭链接数据库下达sql指令select语句前言:本节内容介绍使用C/

使用Java填充Word模板的操作指南

《使用Java填充Word模板的操作指南》本文介绍了Java填充Word模板的实现方法,包括文本、列表和复选框的填充,首先通过Word域功能设置模板变量,然后使用poi-tl、aspose-words... 目录前言一、设置word模板普通字段列表字段复选框二、代码1. 引入POM2. 模板放入项目3.代码