【问题标题】:launch many transactions typeorm into loop javascript将许多事务 typeorm 启动到循环 javascript
【发布时间】:2022-01-25 20:57:50
【问题描述】:

在我的 Electron 应用中,我想在应用启动时注入数据(如 Fixtures)。

我使用 typeorm 库来管理我的 SQLite3 数据库连接。

我创建了代表实体 typeorm 的 json 文件,我想用 typeorm 将它们全部保存在我的数据库中。为此,似乎使用交易更有效。

我尝试了两种不同的方法,但结果是一样的,我不明白为什么。问题信息是:

错误:给定连接的事务已经开始,提交 开始新交易之前的当前交易

我的第一次交易实现

async setAll(entity, data)
{
    let connection = await this.init()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()

    for (const [key, value] of Object.entries(data))
    {
        await typeorm.getManager().transaction(transactionalEntityManager =>
        {

        })
    }
}

我的第二次交易实现

async setAll(entity, data)
{
    let connection = await this.init()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()

    for (const [key, value] of Object.entries(data))
    {
        let genre1 = new Genre()
        genre1.name = 'toto'
        genre1.identifier = 'gt'
        genre1.logo = ''
        genre1.isActivate = false

        await queryRunner.startTransaction()
        await queryRunner.manager.save(genre1)
        await queryRunner.commitTransaction()
        await queryRunner.release()
    }
}

注意:第二个实现正确地保留第一个对象,但不保留其他对象。

如何管理许多 typeorm Transaction 创建到循环中以保留大量数据?

【问题讨论】:

    标签: electron typeorm


    【解决方案1】:
    async setAll(entity, data) {
        let connection = await this.init()
        const queryRunner = connection.createQueryRunner()
        await queryRunner.connect()
        await queryRunner.startTransaction()
        try {
            for await (const [key, value] of Object.entries(data)) {
                let genre1 = new Genre()
                genre1.name = 'toto'
                genre1.identifier = 'gt'
                genre1.logo = ''
                genre1.isActivate = false
              const newGenre= queryRunner.manager.create(Genre,genre1)
               await queryRunner.manager.save(newGenre)
            }
    
            await queryRunner.commitTransaction()
        } catch {
            await queryRunner.rollbackTransaction()
        } finally {
            await queryRunner.release()
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 2022-08-11
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      相关资源
      最近更新 更多