【问题标题】:How to use transactions with NestJs Repositories?如何在 NestJs 存储库中使用事务?
【发布时间】:2021-09-17 18:08:55
【问题描述】:

假设我有这个服务:

@Injectable()
export class MyService {
  constructor(
    @InjectRepository(A)
    private aRepository: Repository<A>,
    @InjectRepository(B)
    private bRepository: Repository<B>,
  ) {}

  doSomething() {
     // TX: begin()
    this.aRepository.save(...);
    this.bRepository.save(...);
    // TX: commit()
  }
}

如何启动事务并提交?

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    对于事务,使用注入的存储库不是强制性的。你可以这样做:

    @Injectable()
    export class MyService {
      constructor(
        @InjectRepository(A)
        private aRepository: Repository<A>,
        @InjectRepository(B)
        private bRepository: Repository<B>,
      ) {}
    
      async doSomething() {
        await getManager().transaction(async (manager) => {
          // TX: begin()
          await manager.getRepository(A).save(...);
          await manager.getRepository(B).save(...);
          // TX: commit()
        });
      }
    }
    

    Typeorm Transactions寻找更多信息

    【讨论】:

      猜你喜欢
      • 2020-07-02
      • 2020-06-06
      • 2022-07-07
      • 2022-12-04
      • 2021-12-17
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      相关资源
      最近更新 更多