实体(Entity)
- child::
TypeORM_实体
实体是指数据库中的表格,在TypeORM中用装饰器@Entity来定义。每个实体对应数据库中的一张表,其属性对应表的字段。
指向原始笔记的链接
存储库(Repository)
- child::
TypeORM_存储库
存储库用于操作数据库中的实体数据,通过存储库可以执行增删改查等操作。在TypeORM中使用getRepository方法获取相应实体的存储库。
指向原始笔记的链接const userRepository = getRepository(User); const user = await userRepository.findOne(1);
连接(Connection)
- child::
TypeORM_连接
连接表示与数据库的连接,一个连接可以包含多个存储库。在TypeORM中使用createConnection方法创建一个连接。
指向原始笔记的链接const connection = await createConnection({ type: "mysql", host: "localhost", port: 3306, username: "root", password: "password", database: "mydb", });
数据源(Data Source)
- child::
TypeORM_DataSource
- father::TypeORM_核心概念
梗概
Data Source(数据源)是TypeORM中的一个核心概念,它是一个预定义的数据库连接配置,可以直接用于创建数据库连接。它替代了旧版本中的
createConnection方法,提供了更好的类型支持和更清晰的API。基本用法
创建Data Source
import { DataSource } from "typeorm" const AppDataSource = new DataSource({ type: "mysql", host: "localhost", port: 3306, username: "root", password: "admin", database: "test", entities: [User, Post], synchronize: true, logging: true })初始化连接
// 初始化连接 AppDataSource.initialize() .then(() => { console.log("Data Source has been initialized!") }) .catch((err) => { console.error("Error during Data Source initialization", err) })配置选项
Data Source支持多种配置选项:
-
基本连接信息:
- type: 数据库类型(mysql, postgres等)
- host: 主机地址
- port: 端口号
- username: 用户名
- password: 密码
- database: 数据库名
-
实体相关:
- entities: 实体类数组或实体文件路径
- entityPrefix: 表名前缀
- entitySkipConstructor: 是否跳过实体构造函数
-
同步和日志:
- synchronize: 是否自动同步实体结构到数据库
- logging: 是否启用日志
- logger: 自定义日志器
-
连接池设置:
- poolSize: 连接池大小
- connectionTimeout: 连接超时时间
使用场景
- 单数据库应用:
const AppDataSource = new DataSource({ type: "mysql", database: "test", entities: [User, Post] })- 多数据库应用:
const MainDataSource = new DataSource({ name: "main", type: "mysql", database: "main_db" }) const LogDataSource = new DataSource({ name: "log", type: "mysql", database: "log_db" })最佳实践
- 避免在生产环境使用synchronize
const AppDataSource = new DataSource({ synchronize: process.env.NODE_ENV === "development" })- 使用环境变量配置敏感信息
const AppDataSource = new DataSource({ username: process.env.DB_USERNAME, password: process.env.DB_PASSWORD })- 合理配置连接池
指向原始笔记的链接const AppDataSource = new DataSource({ type: "mysql", poolSize: 10, connectionTimeout: 3000 })
查询构建器(Query Builder)
- child::
TypeORM_链式查询
- base::TypeORM_增删改查
链式查询示例
假设我们有一个名为
User的实体,其中包含id、username和email字段。我们想要从数据库中获取所有用户名为 “Alice” 的用户,并按照 id 降序排序。使用 TypeORM 的链式查询可以轻松实现这个目标:import { createConnection } from 'typeorm'; import { User } from './entity/User'; createConnection().then(async connection => { const users = await connection.getRepository(User) .createQueryBuilder('user') .where('user.username = :username', { username: 'Alice' }) .orderBy('user.id', 'DESC') .getMany(); console.log(users); });在这个示例中,我们首先创建了连接到数据库的连接,并通过
指向原始笔记的链接connection.getRepository(User)获取了User实体的存储库。然后使用createQueryBuilder()方法创建了一个查询构建器,并通过一系列方法链式调用来添加条件和排序选项。最后使用getMany()方法执行查询并获取结果。