TypeORM 事务有两种方式来管理事务

在TypeORM中,可以使用两种方式来管理事务:

使用数据库连接对象的createQueryRunner()方法来创建一个QueryRunner实例,然后在该实例上执行操作并管理事务。使用这种方式,我们可以控制我们的事务以及使用单个数据库连接执行操作。

const queryRunner = connection.createQueryRunner();
await queryRunner.startTransaction();
// execute some operations
await queryRunner.commitTransaction();

使用EntityManager提供的@Transactional()装饰器来控制事务。使用这种方式,TypeORM会自动创建QueryRunner实例并处理事务,我们只需在标记的方法上使用该装饰器即可。

示例代码:

@Entity()
class User {
  // entity properties
}

@Repository()
class UserRepository extends Repository<User> {
  @Transactional()
  async createUser(user: User) {
    await this.save(user);
  }
}