DataSource
什么是 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 文档。
What is a DataSource?
Your interaction with the database is only possible once you setup a DataSource. TypeORM's DataSource holds your database connection settings and establishes the initial database connection or connection pool depending on the RDBMS you use.
To establish the initial connection/connection pool, you must call the initialize method of your DataSource instance.
initialize must only be called once: calling it again while a previous call is still in progress, or after it has succeeded, rejects with a CannotConnectAlreadyConnectedError. If initialization fails, the partially established connection is cleaned up and initialize can safely be called again.
Disconnection (closing all connections in the pool) occurs when the destroy method is called.
Generally, you call the initialize method of the DataSource instance on the application bootstrap, and destroy it after you finished working with the database. In practice, if you are building a backend for your site and your backend server always stays running - you never destroy a DataSource.
Creating a new DataSource
To create a new DataSource instance you must initialize its constructor by calling new DataSource and assigning to a global variable that you'll use across your application:
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)
}It's a good idea to make AppDataSource globally available by export-ing it since you'll use this instance across your application.
DataSource accepts DataSourceOptions and those options vary depending on the database type you use. For different database types, there are different options you can specify.
You can define as many data sources as you need in your application, for example:
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}"],
})How to use DataSource?
Once you set your DataSource, you can use it anywhere in your app, for example:
import { AppDataSource } from "./app-data-source"
import { User } from "../entity/User"
export class UserController {
@Get("/users")
getAll() {
return AppDataSource.manager.find(User)
}
}Using the DataSource instance you can execute database operations with your entities, particularly using .manager and .getRepository() properties. For more information about them see Entity Manager and Repository documentation.