- TypeORM 教程
- TypeORM - 主頁
- TypeORM - 介紹
- TypeORM - 安裝
- TypeORM - 建立一個簡單專案
- TypeORM - 連線 API
- TypeORM - 實體
- TypeORM - 關係
- TypeORM - 使用儲存庫
- TypeORM - 使用實體管理器
- TypeORM - 查詢構建器
- TypeORM - 查詢操作
- TypeORM - 事務
- TypeORM - 索引
- TypeORM - 實體偵聽器和日誌記錄
- TypeORM 與 JavaScript
- TypeORM - 使用 MongoDB
- TypeORM 與 Express
- TypeORM - 遷移
- TypeORM - 使用 CLI
- TypeORM 有用資源
- TypeORM - 快速指南
- TypeORM - 有用資源
- TypeORM - 討論
TypeORM - 事務
一般來說,事務是一個負責執行資料檢索和更新的邏輯單元。本部分詳細解釋事務。
建立事務
我們可以使用連線或 EntityManage 建立事務。以下示例用於指定建立連線並儲存其內部資料。
import {getConnection} from "typeorm";
await getConnection().transaction(async transactionalEntityManager => {
await connection.manager.save(students);
});
EntityManager 如下所示 −
import {getManager} from "typeorm";
await getManager().transaction(async transactionalEntityManager => {
await transactionalEntityManager.save(students);
});
裝飾器
在 TypeORM 中,我們有三種與事務相關的裝飾器。
- @Transaction - 將所有執行封裝在一個數據庫事務中。
- @TransactionManager - 用於在事務內部執行查詢。如下定義,
@Transaction({ isolation: "SERIALIZABLE" })
save(@TransactionManager() manager: EntityManager, student: Student) {
return manager.save(student);
}
此處,
我們對事務使用了 SERIALIZABLE 隔離級別。
- @TransactionRepository - 用於在儲存庫中注入事務。如下定義,
@Transaction() save(student: Student, @TransactionRepository(Student) studentRepository:
Repository<Student>) {
return studentRepository.save(student);
}
QueryRunner 中的事務
QueryRunner 用於執行所有資料庫查詢。它只有一個數據庫連線。可以使用 QueryRunner 組織資料庫事務。讓我們使用 QueryRunner 執行單一事務。
import {getConnection} from "typeorm";
// get a connection and create a new query runner
const connection = getConnection(); const queryRunner = connection.createQueryRunner();
// establish real database connection using our new query runner
await queryRunner.connect();
// now we can execute any queries on a query runner, for example: await queryRunner.query("SELECT * FROM students");
現在,使用以下語句啟動事務 −
await queryRunner.startTransaction();
然後,使用以下語句提交併回滾事務,
try {
await queryRunner.commitTransaction();
}
如果出現任何錯誤,則由 catch() 處理,
catch (err) {
// since we have errors lets rollback changes we made await queryRunner.rollbackTransaction();
}
現在,如下釋放 queryRunner −
finally {
// you need to release query runner which is manually created: await queryRunner.release();
}
廣告