德胜云资讯,添加一些关于程序相关的内容,仅供大家学习交流(https://www.wxclwl.com)
日期:2023/03/26 06:25作者:吴思翰人气:
typescript 是微软开发的一个开源的编程语言,通过在 javascript 的基础上添加静态类型定义构建而成。TypeScript 拥有更为强大的特性,更适合开发大型 Web 应用。而当进行数据相关的开发时,一个合适的 ORM 尤为重要。
TypeORM
TypeORM,是 typeorm 组织在 Github 上开源的 TypeScript 数据库 ORM,目前版本为 0.2.31。
TypeORM 可以运行在 NodeJS、浏览器、React Native 等平台上,支持使用 TypeScript 和 JavaScript ES5 到 ES8。TypeORM 为开发数据库相关应用提供帮助,从只有数个表的小应用,到大型的企业应用,都可以使用 TypeORM 来完成数据库操作开发。
TypeORM 支持 Active Record 模式和 Data Mapper 模式,开发者可以自行选择,编写高质量、松耦合、可扩展、可维护的数据库应用。
TypeORM
要使用 TypeORM,使用 NPM 安装:
npm install typeorm --save npm install @types/node --save-dev另外,还需要安装 reflect-metadata,并在全局引用:
npm install reflect-metadata --save import "reflect-metadata";想要连接对应的数据库,需要安装对应的数据库驱动,如 MySql 的驱动 mysql,SQLite 的 sqlite3,MongoDB 的 mongodb。
TypeORM 需要 TypeScript 3.3 +,并需要在 tsconfig.json 中添加配置:
"emitDecoratorMetadata": true, "experimentalDecorators": true,TypeORM
使用 TypeORM,最简单的方法是直接使用 typeorm 命令行工具:
typeorm init --name MyProject --database mysql这个命令会创建以下的项目:
MyProject ├── src // place of your TypeScript code │ ├── entity // place where your entities (database models) are stored │ │ └── User.ts // sample entity │ ├── migration // place where your migrations are stored │ └── index.ts // start point of your application ├── .gitignore // standard gitignore file ├── ormconfig.json // ORM and database connection configuration ├── package.json // node module dependencies ├── README.md // simple readme file └── tsconfig.json // TypeScript compiler options然后进入文件夹,并安装依赖:
cd MyProject npm install编辑项目中的 ormconfig.json 文件,并填写数据库连接的参数,包括数据、用户名、密码等等:
{ "type": "mysql", "host": "localhost", "port": 3306, "username": "test", "password": "test", "database": "test", "synchronize": true, "logging": false, "entities": [ "src/entity/**/*.ts" ], "migrations": [ "src/migration/**/*.ts" ], "subscribers": [ "src/subscriber/**/*.ts" ] }然后运行:
npm start我们就可以成功运行项目了。在此基础上,我们可以添加其他模块,实现自定义的功能。
TypeORM
让我们来看一看如何使用 TypeORM 定义数据模型:
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"; @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; }使用 typeorm 提供的 Entity 装饰器定义一个数据实体,使用 PrimaryGeneratedColumn 定义一个自增主键列,使用 Column 定义数据表的列,可以提供包括数据类型等的参数。
定义完数据模型后,就可以连接数据库了:
import "reflect-metadata"; import { createConnection } from "typeorm"; import { Photo } from "./entity/Photo"; createConnection({ type: "mysql", host: "localhost", port: 3306, username: "root", password: "admin", database: "test", entities: [ Photo ], synchronize: true, logging: false }).then(connection => { // here you can start to work with your entities }).catch(error => console.log(error));数据的查询,使用 async / await 语法,使用 find、findOne、findAndCount 等一系列方法:
import { createConnection } from "typeorm"; import { Photo } from "./entity/Photo"; createConnection(/*...*/).then(async connection => { /*...*/ let allPhotos = await photoRepository.find(); console.log("All photos from the db: ", allPhotos); let firstPhoto = await photoRepository.findOne(1); console.log("First photo from the db: ", firstPhoto); let meAndBearsPhoto = await photoRepository.findOne({ name: "Me and Bears" }); console.log("Me and Bears photo from the db: ", meAndBearsPhoto); let allViewedPhotos = await photoRepository.find({ views: 1 }); console.log("All viewed photos: ", allViewedPhotos); let allPublishedPhotos = await photoRepository.find({ isPublished: true }); console.log("All published photos: ", allPublishedPhotos); let [allPhotos, photosCount] = await photoRepository.findAndCount(); console.log("All photos: ", allPhotos); console.log("Photos count: ", photosCount); }).catch(error => console.log(error));TypeORM 使用 TypeScript 的高级特性,实现了一个具有很高抽象层次的数据库 ORM,功能强大,使 TypeScript 能够高效开发数据库应用,值得使用。
TypeORM