返回
Featured image of post TypeORM - QueryRunner & Transactions

TypeORM - QueryRunner & Transactions

QueryRunner - manually control your database transaction

20220930-備註更新 此篇文章為 0.2.x


什麼是 QueryRunner ?

每個 QueryRunner 都是一個單獨的數據庫連接

import {getConnection} from "typeorm";

// 建立運行器
const queryRunner = getConnection().createQueryRunner();

// 建立連線
await queryRunner.connect();

// 啟動新事務
await queryRunner.startTransaction();

try {
    
    // 運算相關交握
    await queryRunner.manager.save(user1);
    await queryRunner.manager.save(user2);
    await queryRunner.manager.save(photos);
    
    // 提交事務
    await queryRunner.commitTransaction();
    
} catch (err) {
    
    // 若錯誤 事務rollback
    await queryRunner.rollbackTransaction();
    
} finally {
    
    // 釋放運行器
    await queryRunner.release();
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus