Typeorm的学习和使用(集成在Express api框架中)


一、Express搭建

参考 Nodejs + Typescript + Express框架搭建 快速搭建Express Api框架

二、安装MySql数据库

安装MySql步骤资料很多,自行查询。

三、Typeorm 安装

1. 简介

TypeORM是一种可以在NodeJS、Browser、Cordova、PhoneGap、Ionic、React Native、NativeScript、Expo和Electron平台上运行的ORM(对象关系映射Object Relational Mapping,简称ORM),可以与TypeScript和JavaScript(ES5、ES6、ES7、ES8)一起使用。它的目标是始终支持最新的JavaScript功能,并提供其他功能,帮助您开发使用数据库的任何类型的应用程序—从具有几个表的小型应用程序到具有多个数据库的大型企业应用程序。

2. 安装

安装typeorm npm包

npm install typeorm --save

安装 reflect-metadata(创建连接处需要import在database.ts文件中)

npm install reflect-metadata --save

安装 node typings(以此来使用 Node 的智能提示)

npm install @types/node --save

安装数据库驱动

//Mysql
npm install mysql --save
//PostgreSQL
npm install pg --save
//SqlServer
npm install mssql --save
//Sqlite
npm install sqlite3 --save

更新tsconfig.json

"experimentalDecorators": true,    
"emitDecoratorMetadata": true,  

3. 创建实体

创建photo.ts
PrimaryGeneratedColumn 自增主键
@Column photo表中的列
length: 100 可以给列设置最大长度
@Column(“text”) @Column(“double”) 给列设置类型

import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";
// PrimaryGeneratedColumn 自增主键
// @Column photo表中的列
// length: 100 可以给列设置最大长度
// @Column("text") @Column("double") 给列设置类型
@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id?: number;

    @Column({
        length: 100,
    })
    name?: string;

    @Column("text")
    description?: string;

    @Column()
    filename?: string;

    @Column("double")
    views?: number;

    @Column()
    isPublished?: boolean;
}

创建数据库连接database.ts
import "reflect-metadata"创建数据库连接处需要引入
createConnection 用来创建连接 内部为连接参数 type: “mysql”,host: “localhost”,等等
isConnected 判断数据库是否为连接中
使用EntityManger可以直接操作对应Entity进行增删改查 defualtConnection.manager.save(entity)
将通用方法export出去来方便使用
使用Repositories 可以更好的操作Entity
entities: [Photo] 用来将Photo 添加到实体列表中,真正开发不可能只有一个表,按照以下写法将全部实体添加
entities: [__dirname + “/entity/*.ts”]

import "reflect-metadata";
import { createConnection, Connection } from "typeorm";
import { Photo } from "../entity/Photo";

// mport "reflect-metadata"创建数据库连接处需要引入

// createConnection 用来创建连接 内部为连接参数 type: "mysql",host: "localhost",等等

// isConnected 判断数据库是否为连接中

// 使用EntityManger可以直接操作对应Entity进行增删改查 defualtConnection.manager.save(entity)

// 将通用方法export出去来方便使用

//使用Repositories 可以更好的操作Entity

//entities: [Photo] 用来将Photo 添加到实体列表中,真正开发不可能只有一个表,按照以下写法将全部实体添加
//entities: [__dirname + "/entity/*.ts"] 

let defualtConnection:Connection
async function initDatabase(){
    if (!!defualtConnection && defualtConnection.isConnected) {
        return defualtConnection
    }
   const connection = await createConnection({
        type: "mysql",
        host: "localhost",
        port: 3306,
        username: "root",
        password: "123456",
        database: "express",
        entities: [Photo],
        synchronize: true,
        logging: false,
    })
    defualtConnection = connection
    return defualtConnection
}

async function save(entity:any){
    if (!defualtConnection || !defualtConnection.isConnected) {
        await initDatabase()
    }

    return await defualtConnection.manager.save(entity)
}
async function getAll(entity:any){
    if (!defualtConnection || !defualtConnection.isConnected) {
        await initDatabase()
    }
    return await defualtConnection.manager.find(entity)
}

async function getRepository(entity:any){
    if (!defualtConnection || !defualtConnection.isConnected) {
        await initDatabase()
    }
    return await defualtConnection.getRepository(entity)
}
export {
    initDatabase,
    save,
    getAll,
    getRepository
}

启动Express,当调用创建连接时对应表会自动创建到DB中

四、使用Typeorm进行增删改查

整体代码结构如下:
整体代码结构
增 – 插入Photo表数据

//通过http请求传入body 插入数据库 (/routes/index.ts)
export let savePhoto = async (req: Request, res: Response) => {
    const body = req.body
    let photo = new Photo();
    photo.name =  body.name;
    photo.description = body.description;
    photo.filename = body.filename;
    photo.views = body.views;
    photo.isPublished = body.isPublished;
    res.send({data: await DataProvider.PhotoDao.savePhoto(photo)})
}

//使用defualtConnection.manager.save(entity) 将ptoto保存 (dao/photo.ts)
savePhoto: async (entity:any) => {
     return await DataProvider.DataBase.save(entity)
}
/// dao/database.ts
async function save(entity:any){
    if (!defualtConnection || !defualtConnection.isConnected) {
        await initDatabase()
    }

    return await defualtConnection.manager.save(entity)
}

查询 – 根据条件查询Photo
用id作为条件来查询有两种方式 params和query
当请求是 http://localhost:8888/findPhotoById/2,使用const { id } = req.params 获取id
当请求使用query http://localhost:8888/findPhotoByIdWithQuery?id=1 使用 const id = req.query.id 获取id
dao中都是用getRepository 来用id查询后返回

export let findPhotoById = async (req: Request,res: Response) =>{
    //http://localhost:8888/findPhotoById/2
    const { id } = req.params
    res.send({data: await DataProvider.PhotoDao.getPhotoById(+id)})
}

export let findPhotoByIdWithQuery = async (req: Request,res: Response) =>{
	//http://localhost:8888/findPhotoByIdWithQuery?id=1
    const id = req.query.id
    res.send({data: await DataProvider.PhotoDao.getPhotoById(Number(id))})
}

//dao中写法

    getPhotoById: async (id: number) =>{
        const getRepository =  await DataProvider.DataBase.getRepository(Photo)
        return await getRepository.find({id:id})
    },

更新
使用getRepository.save 按照实际需求来更新数据库

 updatePhoto:async (entity:any) => {
     const getRepository =  await DataProvider.DataBase.getRepository(Photo)
     let photo = await getRepository.findOne({id:entity.id}) as Photo
     photo.name = entity.name
     return await getRepository.save(photo)
 },

删除
使用getRepository.remove按照实际需求来删除Photo

 delete:async(id:number) => {
     const getRepository = await DataProvider.DataBase.getRepository(Photo)
     const photo = await getRepository.findOne({id:id}) as Photo
     return await getRepository.remove(photo)
 }

五、文章中代码git地址

文章中代码 github 地址

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值