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更新某个字段拼接固定字符串的实现

《MySQL更新某个字段拼接固定字符串的实现》在MySQL中,我们经常需要对数据库中的某个字段进行更新操作,本文就来介绍一下MySQL更新某个字段拼接固定字符串的实现,感兴趣的可以了解一下... 目录1. 查看字段当前值2. 更新字段拼接固定字符串3. 验证更新结果mysql更新某个字段拼接固定字符串 -

python连接本地SQL server详细图文教程

《python连接本地SQLserver详细图文教程》在数据分析领域,经常需要从数据库中获取数据进行分析和处理,下面:本文主要介绍python连接本地SQLserver的相关资料,文中通过代码... 目录一.设置本地账号1.新建用户2.开启双重验证3,开启TCP/IP本地服务二js.python连接实例1.

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

Ubuntu中远程连接Mysql数据库的详细图文教程

《Ubuntu中远程连接Mysql数据库的详细图文教程》Ubuntu是一个以桌面应用为主的Linux发行版操作系统,这篇文章主要为大家详细介绍了Ubuntu中远程连接Mysql数据库的详细图文教程,有... 目录1、版本2、检查有没有mysql2.1 查询是否安装了Mysql包2.2 查看Mysql版本2.

基于SpringBoot+Mybatis实现Mysql分表

《基于SpringBoot+Mybatis实现Mysql分表》这篇文章主要为大家详细介绍了基于SpringBoot+Mybatis实现Mysql分表的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录基本思路定义注解创建ThreadLocal创建拦截器业务处理基本思路1.根据创建时间字段按年进

Python3.6连接MySQL的详细步骤

《Python3.6连接MySQL的详细步骤》在现代Web开发和数据处理中,Python与数据库的交互是必不可少的一部分,MySQL作为最流行的开源关系型数据库管理系统之一,与Python的结合可以实... 目录环境准备安装python 3.6安装mysql安装pymysql库连接到MySQL建立连接执行S

MySQL双主搭建+keepalived高可用的实现

《MySQL双主搭建+keepalived高可用的实现》本文主要介绍了MySQL双主搭建+keepalived高可用的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、测试环境准备二、主从搭建1.创建复制用户2.创建复制关系3.开启复制,确认复制是否成功4.同

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

MyBatis 动态 SQL 优化之标签的实战与技巧(常见用法)

《MyBatis动态SQL优化之标签的实战与技巧(常见用法)》本文通过详细的示例和实际应用场景,介绍了如何有效利用这些标签来优化MyBatis配置,提升开发效率,确保SQL的高效执行和安全性,感... 目录动态SQL详解一、动态SQL的核心概念1.1 什么是动态SQL?1.2 动态SQL的优点1.3 动态S

Mysql表的简单操作(基本技能)

《Mysql表的简单操作(基本技能)》在数据库中,表的操作主要包括表的创建、查看、修改、删除等,了解如何操作这些表是数据库管理和开发的基本技能,本文给大家介绍Mysql表的简单操作,感兴趣的朋友一起看... 目录3.1 创建表 3.2 查看表结构3.3 修改表3.4 实践案例:修改表在数据库中,表的操作主要