NestJS入门4:MySQL typeorm 增删改查

2024-02-20 07:12

本文主要是介绍NestJS入门4:MySQL typeorm 增删改查,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  前文参考:

NestJS入门1

NestJS入门2:创建模块

NestJS入门3:不同请求方式前后端写法

1. 安装数据库相关模块

npm install @nestjs/typeorm typeorm mysql -S

2. MySql中创建数据库

3. 添加连接数据库代码

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from "./user/user.module";
import { TypeOrmModule } from "@nestjs/typeorm";@Module({imports: [UserModule,TypeOrmModule.forRoot({type: "mysql",host: "localhost",port: 3306,username: "root",password: "root",database: "user",entities: ["dist/**/*.entity{.ts,.js}"],synchronize: true,}),],controllers: [AppController],providers: [AppService],
})
export class AppModule {}

4. 创建数据表

user/entities/user.entity.ts修改为

import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";@Entity("user")//数据表名称,由本程序创建
export class UserEntity {@PrimaryGeneratedColumn()id: number; // 标记为主键,值自动生成@Column({ length: 20 })username: string;@Column({ length: 20 })password: string;@Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })create_time: Date;@Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })update_time: Date;
}

以上代码重新运行后,可以看到数据表

5.  user.module导入并注册实体

import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { UserEntity } from "./entities/user.entity"; //增加语句
import { TypeOrmModule } from "@nestjs/typeorm"; // 增加语句@Module({imports: [TypeOrmModule.forFeature([UserEntity])], //增加语句:导入并注册实体controllers: [UserController],providers: [UserService],
})
export class UserModule {}

6. user.services增加数据库操作

import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserEntity } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';@Injectable()
export class UserService {constructor(@InjectRepository(UserEntity)private userRepository: Repository<UserEntity>,) {}// 增加async create(createUserDto: CreateUserDto) {this.userRepository.save(createUserDto);}// 查询所有async findAll() {return await this.userRepository.find();}// 查询特定
async findOne(id: number) {return await this.userRepository.findOne({where:{id:id}});}// 更新 async  update(id: number, updateUserDto: UpdateUserDto) {return await this.userRepository.update({id:id}, updateUserDto);}// 删除  
async  remove(id: number) {return await this.userRepository.delete({id:id});}
}

user.controller.ts不需要修改

import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';@Controller('user')
export class UserController {constructor(private readonly userService: UserService) {}// POST http://localhost:3000/user  Body加上X-www-form-urlencoded数据   @Post()create(@Body() createUserDto: CreateUserDto) {return this.userService.create(createUserDto);}//GET http://localhost:3000/user@Get()findAll() {console.log('Get');return this.userService.findAll();}//GET http://localhost:3000/user/1@Get(':id')findOne(@Param('id') id: string) {console.log('Get ' + id);return this.userService.findOne(+id);}//PATCH http://localhost:3000/user/1  Body加上数据@Patch(':id')update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {console.log('Patch ' + id);console.log(UpdateUserDto);return this.userService.update(+id, updateUserDto);}//DELETE http://localhost:3000/user/1 @Delete(':id')remove(@Param('id') id: string) {console.log('Delete ' + id);return this.userService.remove(+id);}
}

7. 运行验证

以上代码通过post可以数据到数据库,如下

(1)增加

(3)查询所有

(4)查询单个

(5)更新

(2)删除

这篇关于NestJS入门4:MySQL typeorm 增删改查的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

mysql_mcp_server部署及应用实践案例

《mysql_mcp_server部署及应用实践案例》文章介绍了在CentOS7.5环境下部署MySQL_mcp_server的步骤,包括服务安装、配置和启动,还提供了一个基于Dify工作流的应用案例... 目录mysql_mcp_server部署及应用案例1. 服务安装1.1. 下载源码1.2. 创建独立

Mysql中RelayLog中继日志的使用

《Mysql中RelayLog中继日志的使用》MySQLRelayLog中继日志是主从复制架构中的核心组件,负责将从主库获取的Binlog事件暂存并应用到从库,本文就来详细的介绍一下RelayLog中... 目录一、什么是 Relay Log(中继日志)二、Relay Log 的工作流程三、Relay Lo

MySQL日志UndoLog的作用

《MySQL日志UndoLog的作用》UndoLog是InnoDB用于事务回滚和MVCC的重要机制,本文主要介绍了MySQL日志UndoLog的作用,文中介绍的非常详细,对大家的学习或者工作具有一定的... 目录一、Undo Log 的作用二、Undo Log 的分类三、Undo Log 的存储四、Undo

MySQL游标和触发器的操作流程

《MySQL游标和触发器的操作流程》本文介绍了MySQL中的游标和触发器的使用方法,游标可以对查询结果集进行逐行处理,而触发器则可以在数据表发生更改时自动执行预定义的操作,感兴趣的朋友跟随小编一起看看... 目录游标游标的操作流程1. 定义游标2.打开游标3.利用游标检索数据4.关闭游标例题触发器触发器的基

MySQL查看表的历史SQL的几种实现方法

《MySQL查看表的历史SQL的几种实现方法》:本文主要介绍多种查看MySQL表历史SQL的方法,包括通用查询日志、慢查询日志、performance_schema、binlog、第三方工具等,并... 目录mysql 查看某张表的历史SQL1.查看MySQL通用查询日志(需提前开启)2.查看慢查询日志3.

MySQL底层文件的查看和修改方法

《MySQL底层文件的查看和修改方法》MySQL底层文件分为文本类(可安全查看/修改)和二进制类(禁止手动操作),以下按「查看方法、修改方法、风险管控三部分详细说明,所有操作均以Linux环境为例,需... 目录引言一、mysql 底层文件的查看方法1. 先定位核心文件路径(基础前提)2. 文本类文件(可直

MySQL数据目录迁移的完整过程

《MySQL数据目录迁移的完整过程》文章详细介绍了将MySQL数据目录迁移到新硬盘的整个过程,包括新硬盘挂载、创建新的数据目录、迁移数据(推荐使用两遍rsync方案)、修改MySQL配置文件和重启验证... 目录1,新硬盘挂载(如果有的话)2,创建新的 mysql 数据目录3,迁移 MySQL 数据(推荐两

MySQL字符串转数值的方法全解析

《MySQL字符串转数值的方法全解析》在MySQL开发中,字符串与数值的转换是高频操作,本文从隐式转换原理、显式转换方法、典型场景案例、风险防控四个维度系统梳理,助您精准掌握这一核心技能,需要的朋友可... 目录一、隐式转换:自动但需警惕的&ld编程quo;双刃剑”二、显式转换:三大核心方法详解三、典型场景

MySQL中between and的基本用法、范围查询示例详解

《MySQL中betweenand的基本用法、范围查询示例详解》BETWEENAND操作符在MySQL中用于选择在两个值之间的数据,包括边界值,它支持数值和日期类型,示例展示了如何使用BETWEEN... 目录一、between and语法二、使用示例2.1、betwphpeen and数值查询2.2、be

MySQL快速复制一张表的四种核心方法(包括表结构和数据)

《MySQL快速复制一张表的四种核心方法(包括表结构和数据)》本文详细介绍了四种复制MySQL表(结构+数据)的方法,并对每种方法进行了对比分析,适用于不同场景和数据量的复制需求,特别是针对超大表(1... 目录一、mysql 复制表(结构+数据)的 4 种核心方法(面试结构化回答)方法 1:CREATE