NestJS
NestJS 数据库实战:TypeORM 实体映射、Repository 模式与事务控制
Waitwalker2026-08-2416 min
## 1. QueryRunner 编程式事务实战
```typescript
async transferFunds(fromId: number, toId: number, amount: number) {
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
await queryRunner.manager.decrement(Account, { id: fromId }, "balance", amount);
await queryRunner.manager.increment(Account, { id: toId }, "balance", amount);
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
throw err;
} finally {
await queryRunner.release();
}
}
```
#NestJS#TypeORM#MySQL/PostgreSQL#事务
回到文章列表 →