网站搜索

postgresql - TypeORM 不支持在实体装饰器上设置数据库


我正在尝试将我的 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 的一个 bug?在我看来,它似乎不再遵守 database 设置了。

我正在使用 ts-node-dev 运行代码

我创建了一个完整的最小可复现示例,包括数据库环境的 Docker 化设置,在 GitHub 上:https://github.com/petterroea/TypeOrmBug-MRE

答案#1

这是一个设置问题。我是这样解决的:

  1. 修改数组 entities,使每个连接/数据库都有自己的实体文件夹,并将你使用最多的实体命名为 default:
// 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"],
    ])
  1. 在各自的文件夹中为每个数据库创建实体文件:

    • src/db1/entity/Fruit.ts > db1 中的表
    • src/db2/entity/Vegetables.ts > db2中的表

使用 "synchronize": true 时,每个表将自动在正确的数据库中创建

  1. 访问表中的数据:

    • 对于 default 连接:
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()
  }

我希望这能帮助其他和你我有相同问题的人。