Guide to Using TypeORM Transactions


Guide to Using TypeORM Transactions

What are TypeORM Transactions?

The use of TypeORM Transactions comes into play when you want to securely and consistently perform multiple database operations in your application. A transaction ensures the principle that a group of operations either all succeed together or, if one fails, none are executed. By correctly using transactions with TypeORM, you can preserve data integrity, especially in critical fields such as banking or e-commerce.

How to Use TypeORM Transactions?

Transactions in TypeORM can be managed through several different methods. The most commonly used are the @Transaction() decorator and the manual transaction initiation method with QueryRunner. For complex operations, QueryRunner is generally preferred as it provides full control over the process.

Using with @Transaction Decorator

import { Transaction, TransactionManager, EntityManager } from "typeorm";

export class UserService {
  @Transaction()
  async createUserAndProfile(
    userData: any,
    @TransactionManager() manager?: EntityManager,
  ) {
    const user = await manager.save(User, userData);
    const profile = await manager.save(Profile, { userId: user.id });
    return { user, profile };
  }
}

In this example, inserts into the User and Profile tables are executed within a single transaction. This means if an error occurs at any step, all operations are rolled back.

Manual Transaction with QueryRunner

import { getConnection } from "typeorm";

const connection = getConnection();
const queryRunner = connection.createQueryRunner();

await queryRunner.connect();
await queryRunner.startTransaction();
try {
  await queryRunner.manager.save(User, { name: "Ahmet" });
  await queryRunner.manager.save(Profile, { bio: "Yazılımcı" });
  await queryRunner.commitTransaction();
} catch (err) {
  await queryRunner.rollbackTransaction();
} finally {
  await queryRunner.release();
}

With QueryRunner, you can control the operations manually to provide a more flexible and secure transaction management. It is ideal especially for complex operations involving multiple tables or business rules.

Conclusion: Advantages of Using TypeORM Transactions

The use of TypeORM Transactions provides great convenience for data integrity and error management in your Node.js projects. Positioning transaction use correctly makes your code both more robust and more secure. Especially in financial transactions or critical data updates, transactions are indispensable. From an SEO perspective, for both beginners and advanced developers, the use of TypeORM Transactions offers advantages of readable code and data security.