TypeORM 不会在失败时回滚

问题描述

我是 TypeORM 和 pg 的新手,我已经声明了一个扩展 BaseEntity 的类“用户”。我创建了类添加值的实例(用户)(user.name = 'Arun'),然后在 user.save() 上因数据库约束而失败。似乎 TypeORM 没有恢复提交。 here 自动生成的 ID 不是增量的,因为没有回滚。我是否错过了回滚的任何配置?我想知道使用构造函数创建 TypeORM 模型的任何更好的例子。

解决方法

默认情况下,TypeORM 查询不是事务性的。

如果您想使用事务在失败时回滚查询,则需要 EntityManager

import {getManager} from "typeorm";

await getManager().transaction(async transactionalEntityManager => {
    await transactionalEntityManager.save(users);
    await transactionalEntityManager.save(photos);
    // ...
});

文档 here 了解有关 TypeORM 事务的更多信息。