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

相关文章

Linux下MySQL数据库定时备份脚本与Crontab配置教学

《Linux下MySQL数据库定时备份脚本与Crontab配置教学》在生产环境中,数据库是核心资产之一,定期备份数据库可以有效防止意外数据丢失,本文将分享一份MySQL定时备份脚本,并讲解如何通过cr... 目录备份脚本详解脚本功能说明授权与可执行权限使用 Crontab 定时执行编辑 Crontab添加定

从入门到精通详解Python虚拟环境完全指南

《从入门到精通详解Python虚拟环境完全指南》Python虚拟环境是一个独立的Python运行环境,它允许你为不同的项目创建隔离的Python环境,下面小编就来和大家详细介绍一下吧... 目录什么是python虚拟环境一、使用venv创建和管理虚拟环境1.1 创建虚拟环境1.2 激活虚拟环境1.3 验证虚

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

MySQL分库分表的实践示例

《MySQL分库分表的实践示例》MySQL分库分表适用于数据量大或并发压力高的场景,核心技术包括水平/垂直分片和分库,需应对分布式事务、跨库查询等挑战,通过中间件和解决方案实现,最佳实践为合理策略、备... 目录一、分库分表的触发条件1.1 数据量阈值1.2 并发压力二、分库分表的核心技术模块2.1 水平分

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据

Mac电脑如何通过 IntelliJ IDEA 远程连接 MySQL

《Mac电脑如何通过IntelliJIDEA远程连接MySQL》本文详解Mac通过IntelliJIDEA远程连接MySQL的步骤,本文通过图文并茂的形式给大家介绍的非常详细,感兴趣的朋友跟... 目录MAC电脑通过 IntelliJ IDEA 远程连接 mysql 的详细教程一、前缀条件确认二、打开 ID

MySQL的配置文件详解及实例代码

《MySQL的配置文件详解及实例代码》MySQL的配置文件是服务器运行的重要组成部分,用于设置服务器操作的各种参数,下面:本文主要介绍MySQL配置文件的相关资料,文中通过代码介绍的非常详细,需要... 目录前言一、配置文件结构1.[mysqld]2.[client]3.[mysql]4.[mysqldum

MySQL中查询和展示LONGBLOB类型数据的技巧总结

《MySQL中查询和展示LONGBLOB类型数据的技巧总结》在MySQL中LONGBLOB是一种二进制大对象(BLOB)数据类型,用于存储大量的二进制数据,:本文主要介绍MySQL中查询和展示LO... 目录前言1. 查询 LONGBLOB 数据的大小2. 查询并展示 LONGBLOB 数据2.1 转换为十