我正在尝试将我的 TypeORM 项目分离到多个数据库上,因为它的规模不断增长,并且它的组件非常离散(但相互关联,因此我需要能够跨数据库建立关系)。
我正在尝试使用 @Entity
装饰器上的 database
设置来做到这一点,如下所述:https://typeorm.io/#multiple-connections/using-multiple-databases-in-a-single-connection
我为此制作了一个最小的可重现示例,其中两个实体理论上应该放入不同的数据库中:
@Entity({ database: 'test' })
export default class Entity1 {
@PrimaryGeneratedColumn()
id?: number
@Column()
name?: string
@Column()
address?: string
}
和
@Entity({ database: 'database2' })
export default class Entity2 {
@PrimaryGeneratedColumn()
id?: number
@Column()
name?: string
@Column()
address?: string
}
连接代码:
import {createConnections} from "typeorm";
async function doDbExample() {
const connections = await createConnections([{
name: "db1Connection",
type: "postgres",
host: "db",
port: 5432,
username: "test",
password: "testPassword",
database: "test",
entities: [__dirname + "/entity/*{.js,.ts}"],
synchronize: true
}]);
console.log("Created connections")
}
doDbExample()
但是,发生的情况是两个实体的表都放入连接的数据库中。我做错了什么,或者这是 TypeORM 中的错误?在我看来,它不再尊重数据库
设置。
我正在使用ts-node-dev
运行代码
我在 github 上制作了一个完整的最小可重现示例,完成了数据库环境的 Docker 化设置:https://github.com/petterroea/TypeOrmBug-MRE
最佳答案
这是一个设置问题。我是这样解决的:
- 修改数组
entities
,以便每个连接/数据库都有自己的包含实体文件的文件夹,并将您最常使用的实体命名为默认
:
// src/index.ts
await createConnections([
{
name: 'default',
host: 'SERVER1',
username: 'bob',
password: 'kiwi,
type: 'mssql',
database: 'db1',
...
"synchronize": true,
"entities": ["src/db1/entity/**/*.ts"],
},
{
name: 'connection2,
host: 'SERVER2',
username: 'Mike',
password: 'carrot',
type: 'mssql',
database: 'db2,
...
"synchronize": true,
"entities": ["src/db2/entity/**/*.ts"],
])
- 在各自的文件夹中为每个数据库创建实体文件:
src/db1/entity/Fruit.ts
> db1 中的表src/db2/entity/Vegetables.ts
> db2 中的表
使用"synchronize": true
每个表将在正确的数据库中自动创建
- 访问表中的数据:
- 对于
默认
连接::
- 对于
import { Fruit} from 'src/db1/entity/Fruit.ts'
fruits() {
return Fruit.find()
}
- 对于非默认连接:
import { getRepository } from 'typeorm'
import { Vegetable} from 'src/db2/entity/Vegetable.ts'
vegetables() {
return async () => await getRepository(Vegetable).find()
}
或
async vegetables() {
return await getRepository(vegetables, 'connection2').find()
}
我希望这可以帮助其他与你我一样遇到同样问题的人。
关于postgresql - TypeORM 不支持实体装饰器上的数据库设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58891569/