在我的 Electron 应用程序中,我想在应用程序启动时注入(inject)数据(如夹具)。
我使用 typeorm 库来管理我的 SQLite3 数据库连接。
我创建了代表实体 typeorm 的 json 文件,我想用 typeorm 将它们全部保存在我的数据库中。为此,似乎使用事务更有效。
我尝试了两种不同的东西,但结果是一样的,我不明白为什么。问题消息是:
Error: Transaction already started for the given connection, commit current transaction before starting a new one
我第一次执行交易 :
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 事务以持久保存大量数据?
最佳答案
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()
}
关于electron - 将许多事务 typeorm 启动到循环 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944417/