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には、3種類のトランザクション関連のデコレータがあります。

  • @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(); 
}