TypeORM中文文档 v1.1
数据源 / DataSource
GitHub

DataSource

DataSource 英文原文 Markdown

什么是 DataSource?

只有先配置好 DataSource,你才能与数据库交互。TypeORM 的 DataSource 持有你的数据库连接配置,并根据你所使用的 RDBMS 建立初始数据库连接或连接池。

要建立初始连接 / 连接池,你必须调用 DataSource 实例的 initialize 方法。

initialize 只能调用一次:如果在上一次调用仍在进行中时再次调用,或者在它已经成功之后再调用,都会以 CannotConnectAlreadyConnectedError 拒绝。如果初始化失败,已部分建立的连接会被清理掉,此后可以安全地再次调用 initialize。

断开连接(关闭池中的所有连接)发生在调用 destroy 方法时。

通常,你在应用启动时调用 DataSource 实例的 initialize 方法,并在用完数据库之后 destroy 它。实际中,如果你在为自己的站点构建后端,并且后端服务始终常驻运行——你永远不需要 destroy 一个 DataSource。

创建新的 DataSource

要创建一个新的 DataSource 实例,你必须通过调用 new DataSource 来初始化它的构造函数,并把它赋值给一个在整个应用中都会用到的全局变量:

import { DataSource } from "typeorm"

const AppDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
})

try {
    await AppDataSource.initialize()
    console.log("Data Source has been initialized!")
} catch (error) {
    console.error("Error during Data Source initialization", error)
}

把 AppDataSource 用 export 导出、让它在全局可用是个好主意,因为你会在整个应用中都用到这个实例。

DataSource 接受 DataSourceOptions,而这些选项会因你使用的数据库 type 而异。针对不同的数据库类型,你可以指定不同的选项。

你可以在应用中定义任意多个需要的数据源,例如:

import { DataSource } from "typeorm"

const MysqlDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
})

const PostgresDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
})

如何使用 DataSource?

配置好 DataSource 之后,你就可以在应用的任何地方使用它,例如:

import { AppDataSource } from "./app-data-source"
import { User } from "../entity/User"

export class UserController {
    @Get("/users")
    getAll() {
        return AppDataSource.manager.find(User)
    }
}

借助 DataSource 实例,你可以对实体执行数据库操作,尤其是通过 .manager 和 .getRepository() 这两个属性。关于它们的更多信息,请参阅 Entity Manager 和 Repository 文档。