- 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
})