# 事务

> 英文标题：Transactions
> 官网原文：https://typeorm.io/docs/transactions
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 80 块

---

<!-- EN -->
# Transactions

<!-- ZH -->
# 事务

<!-- EN -->
## Creating and using transactions

<!-- ZH -->
## 创建并使用事务

<!-- EN -->
Transactions are created using `DataSource` or `EntityManager`. Examples:

<!-- ZH -->
事务通过 `DataSource` 或 `EntityManager` 创建。示例：

<!-- EN -->
```typescript
await myDataSource.transaction(async (transactionalEntityManager) => {
    // execute queries using transactionalEntityManager
})
```

<!-- ZH -->
```typescript
await myDataSource.transaction(async (transactionalEntityManager) => {
    // 使用 transactionalEntityManager 执行查询
})
```

<!-- EN -->
or

<!-- ZH -->
或者

<!-- EN -->
```typescript
await myDataSource.manager.transaction(async (transactionalEntityManager) => {
    // execute queries using transactionalEntityManager
})
```

<!-- ZH -->
```typescript
await myDataSource.manager.transaction(async (transactionalEntityManager) => {
    // 使用 transactionalEntityManager 执行查询
})
```

<!-- EN -->
Everything you want to run in a transaction must be executed in a callback:

<!-- ZH -->
你想在事务中运行的一切都必须在回调里执行：

<!-- EN -->
```typescript
await myDataSource.manager.transaction(async (transactionalEntityManager) => {
    await transactionalEntityManager.save(users)
    await transactionalEntityManager.save(photos)
    // ...
})
```

<!-- ZH -->
```typescript
await myDataSource.manager.transaction(async (transactionalEntityManager) => {
    await transactionalEntityManager.save(users)
    await transactionalEntityManager.save(photos)
    // ...
})
```

<!-- EN -->
The most important restriction when working in a transaction is to **ALWAYS** use the provided instance of entity manager - `transactionalEntityManager` in this example. DO NOT USE GLOBAL ENTITY MANAGER. All operations **MUST** be executed using the provided transactional entity manager.

<!-- ZH -->
在事务中工作时最重要的限制是：**始终**使用所提供的 entity manager 实例——本例中即 `transactionalEntityManager`。不要使用全局的 ENTITY MANAGER。所有操作 **必须** 通过所提供的事务型 entity manager 执行。

<!-- EN -->
## Specifying isolation level

<!-- ZH -->
## 指定隔离级别

<!-- EN -->
Specifying the isolation level for the transaction can be done by supplying it as the first parameter:

<!-- ZH -->
可以通过把隔离级别作为第一个参数传入来为事务指定它：

<!-- EN -->
```typescript
await myDataSource.manager.transaction(
    "SERIALIZABLE",
    (transactionalEntityManager) => {},
)
```

<!-- ZH -->
```typescript
await myDataSource.manager.transaction(
    "SERIALIZABLE",
    (transactionalEntityManager) => {},
)
```

<!-- EN -->
## Supported isolation levels

<!-- ZH -->
## 受支持的隔离级别

<!-- EN -->
Isolation level implementations are *not* agnostic across all databases. Each driver declares which levels it supports, and TypeORM will throw an error if you request an unsupported level.

<!-- ZH -->
隔离级别的实现并非在所有数据库上都一致。每个驱动会声明它支持哪些级别，如果你请求了不受支持的级别，TypeORM 会抛出错误。

<!-- EN -->
* ![CockroachDB](/img/databases/cockroachdb.svg "CockroachDB")
* ![Google Spanner](/img/databases/spanner.svg "Google Spanner")
* ![MariaDB](/img/databases/mariadb.svg "MariaDB")
* ![MS SQL Server](/img/databases/mssql.svg "MS SQL Server")
* ![MySQL](/img/databases/mysql.svg "MySQL")
* ![Oracle](/img/databases/oracle.svg "Oracle")
* ![PostgreSQL](/img/databases/postgresql.svg "PostgreSQL")
* ![SAP HANA](/img/databases/sap.svg "SAP HANA")
* ![SQLite](/img/databases/sqlite.svg "SQLite")

<!-- ZH -->
* ![CockroachDB](/img/databases/cockroachdb.svg "CockroachDB")
* ![Google Spanner](/img/databases/spanner.svg "Google Spanner")
* ![MariaDB](/img/databases/mariadb.svg "MariaDB")
* ![MS SQL Server](/img/databases/mssql.svg "MS SQL Server")
* ![MySQL](/img/databases/mysql.svg "MySQL")
* ![Oracle](/img/databases/oracle.svg "Oracle")
* ![PostgreSQL](/img/databases/postgresql.svg "PostgreSQL")
* ![SAP HANA](/img/databases/sap.svg "SAP HANA")
* ![SQLite](/img/databases/sqlite.svg "SQLite")

<!-- EN -->
### CockroachDB

<!-- ZH -->
### CockroachDB

<!-- EN -->
* `READ COMMITTED` — requires the cluster setting `sql.txn.read_committed_isolation.enabled`, which is enabled by default in recent versions
* `REPEATABLE READ` — requires the cluster setting `sql.txn.repeatable_read_isolation.enabled`, which is disabled by default (introduced in v24.3.0)
* `SERIALIZABLE` (default)

<!-- ZH -->
* `READ COMMITTED` —— 需要集群设置 `sql.txn.read_committed_isolation.enabled`，近期版本中默认启用
* `REPEATABLE READ` —— 需要集群设置 `sql.txn.repeatable_read_isolation.enabled`，默认禁用（在 v24.3.0 中引入）
* `SERIALIZABLE`（默认）

<!-- EN -->
CockroachDB maps weaker SQL isolation requests to stronger levels. The fallback behavior depends on the corresponding cluster settings. For example, when you request `READ UNCOMMITTED`, `READ COMMITTED` or `REPEATABLE READ` via SQL (e.g. `BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED`), CockroachDB accepts the syntax and may run the transaction at a stricter level instead:

<!-- ZH -->
CockroachDB 会把较弱的 SQL 隔离请求映射到更强的级别。回退行为取决于相应的集群设置。例如，当你通过 SQL 请求 `READ UNCOMMITTED`、`READ COMMITTED` 或 `REPEATABLE READ` 时（例如 `BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED`），CockroachDB 会接受该语法，但可能改用更严格的级别来运行该事务：

<!-- EN -->
* `READ COMMITTED` → runs as:

<!-- ZH -->
* `READ COMMITTED` → 实际运行为：

<!-- EN -->
  <!-- -->

<!-- ZH -->
  <!-- -->

<!-- EN -->
  * `SERIALIZABLE` if `sql.txn.read_committed_isolation.enabled` is false and `sql.txn.repeatable_read_isolation.enabled` is false
  * `REPEATABLE READ` if `sql.txn.repeatable_read_isolation.enabled` is true and `sql.txn.read_committed_isolation.enabled` is false

<!-- ZH -->
  * 当 `sql.txn.read_committed_isolation.enabled` 为 false 且 `sql.txn.repeatable_read_isolation.enabled` 为 false 时，为 `SERIALIZABLE`
  * 当 `sql.txn.repeatable_read_isolation.enabled` 为 true 且 `sql.txn.read_committed_isolation.enabled` 为 false 时，为 `REPEATABLE READ`

<!-- EN -->
* `READ UNCOMMITTED` → runs as:

<!-- ZH -->
* `READ UNCOMMITTED` → 实际运行为：

<!-- EN -->
  <!-- -->

<!-- ZH -->
  <!-- -->

<!-- EN -->
  * `SERIALIZABLE` if `sql.txn.read_committed_isolation.enabled` is false and `sql.txn.repeatable_read_isolation.enabled` is false
  * `READ COMMITTED` if `sql.txn.read_committed_isolation.enabled` is true
  * `REPEATABLE READ` if `sql.txn.repeatable_read_isolation.enabled` is true and `sql.txn.read_committed_isolation.enabled` is false

<!-- ZH -->
  * 当 `sql.txn.read_committed_isolation.enabled` 为 false 且 `sql.txn.repeatable_read_isolation.enabled` 为 false 时，为 `SERIALIZABLE`
  * 当 `sql.txn.read_committed_isolation.enabled` 为 true 时，为 `READ COMMITTED`
  * 当 `sql.txn.repeatable_read_isolation.enabled` 为 true 且 `sql.txn.read_committed_isolation.enabled` 为 false 时，为 `REPEATABLE READ`

<!-- EN -->
* `REPEATABLE READ` → runs as `SERIALIZABLE` if `sql.txn.repeatable_read_isolation.enabled` is false

<!-- ZH -->
* `REPEATABLE READ` → 当 `sql.txn.repeatable_read_isolation.enabled` 为 false 时，实际运行为 `SERIALIZABLE`

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [CockroachDB Read Committed](https://www.cockroachlabs.com/docs/stable/read-committed)
* [CockroachDB Repeatable Read](https://www.cockroachlabs.com/docs/releases/v24.3.html#:~:text=sql.txn.repeatable_read_isolation.enabled%3A%20defaults%20to%20false.%20When%20set%20to%20true%2C%20the%20following%20statements%20configure%20transactions%20to%20run%20under%20REPEATABLE%20READ%20isolation%2C%20rather%20than%20being%20automatically%20interpreted%20as%20SERIALIZABLE)
* [CockroachDB Transactions](https://www.cockroachlabs.com/docs/stable/transactions)

<!-- ZH -->
* [CockroachDB Read Committed](https://www.cockroachlabs.com/docs/stable/read-committed)
* [CockroachDB Repeatable Read](https://www.cockroachlabs.com/docs/releases/v24.3.html#:~:text=sql.txn.repeatable_read_isolation.enabled%3A%20defaults%20to%20false.%20When%20set%20to%20true%2C%20the%20following%20statements%20configure%20transactions%20to%20run%20under%20REPEATABLE%20READ%20isolation%2C%20rather%20than%20being%20automatically%20interpreted%20as%20SERIALIZABLE)
* [CockroachDB Transactions](https://www.cockroachlabs.com/docs/stable/transactions)

<!-- EN -->
### Google Spanner

<!-- ZH -->
### Google Spanner

<!-- EN -->
* `REPEATABLE READ` \*
* `SERIALIZABLE`

<!-- ZH -->
* `REPEATABLE READ` \*
* `SERIALIZABLE`

<!-- EN -->
\* `REPEATABLE READ` on Spanner is currently in [Preview](https://cloud.google.com/products#product-launch-stages) and not yet generally available. It provides snapshot isolation and permits write-skew anomalies — use `SELECT ... FOR UPDATE` when that matters.

<!-- ZH -->
\* Spanner 上的 `REPEATABLE READ` 目前处于[预览阶段](https://cloud.google.com/products#product-launch-stages)，尚未正式发布。它提供快照隔离并允许写偏斜（write-skew）异常——当这会产生影响时，请使用 `SELECT ... FOR UPDATE`。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Spanner Isolation Levels](https://cloud.google.com/spanner/docs/isolation-levels)
* [Spanner Transactions](https://cloud.google.com/spanner/docs/transactions)

<!-- ZH -->
* [Spanner Isolation Levels](https://cloud.google.com/spanner/docs/isolation-levels)
* [Spanner Transactions](https://cloud.google.com/spanner/docs/transactions)

<!-- EN -->
### MariaDB

<!-- ZH -->
### MariaDB

<!-- EN -->
* `READ UNCOMMITTED`
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`

<!-- ZH -->
* `READ UNCOMMITTED`
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [MariaDB SET TRANSACTION](https://mariadb.com/kb/en/set-transaction/)

<!-- ZH -->
* [MariaDB SET TRANSACTION](https://mariadb.com/kb/en/set-transaction/)

<!-- EN -->
### MS SQL Server

<!-- ZH -->
### MS SQL Server

<!-- EN -->
* `READ UNCOMMITTED`
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`
* `SNAPSHOT`

<!-- ZH -->
* `READ UNCOMMITTED`
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`
* `SNAPSHOT`

<!-- EN -->
Driver-specific options

<!-- ZH -->
驱动专属选项

<!-- EN -->
SQL Server also supports driver-specific `options.isolationLevel` and `options.connectionIsolationLevel` settings, but these are subject to an [upstream pool limitation](https://typeorm.io/docs/drivers/microsoft-sqlserver#connection-pool-does-not-reset-isolation-level). The top-level `isolationLevel` option covered on this page is not affected, because it is applied explicitly on each transaction.

<!-- ZH -->
SQL Server 还支持驱动专属的 `options.isolationLevel` 和 `options.connectionIsolationLevel` 配置，但它们受制于一个[上游连接池限制](https://typeorm.io/docs/drivers/microsoft-sqlserver#connection-pool-does-not-reset-isolation-level)。本页介绍的顶层 `isolationLevel` 选项不受影响，因为它会在每个事务上显式应用。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [SQL Server SET TRANSACTION ISOLATION LEVEL](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql)

<!-- ZH -->
* [SQL Server SET TRANSACTION ISOLATION LEVEL](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql)

<!-- EN -->
### MySQL

<!-- ZH -->
### MySQL

<!-- EN -->
* `READ UNCOMMITTED`
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`

<!-- ZH -->
* `READ UNCOMMITTED`
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`

<!-- EN -->
Aurora MySQL via RDS Data API

<!-- ZH -->
通过 RDS Data API 的 Aurora MySQL

<!-- EN -->
**Isolation levels are not supported on the `aurora-mysql` driver.** Requesting any level throws a validation error.

<!-- ZH -->
**`aurora-mysql` 驱动不支持隔离级别。** 请求任何级别都会抛出校验错误。

<!-- EN -->
This is a transport limitation, not an engine limitation. Aurora MySQL the database engine [fully supports](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Reference.IsolationLevels.html) the standard set, but the `aurora-mysql` driver talks to the cluster over the stateless [RDS Data API](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html) instead of a persistent MySQL protocol connection, and the Data API provides no way to attach an isolation level to a transaction:

<!-- ZH -->
这是传输层的限制，而非引擎层的限制。Aurora MySQL 数据库引擎[完全支持](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Reference.IsolationLevels.html)标准的那一组隔离级别，但 `aurora-mysql` 驱动是通过无状态的 [RDS Data API](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html)而不是常驻的 MySQL 协议连接与集群通信的，而 Data API 没有提供把隔离级别附加到事务上的方法：

<!-- EN -->
* [`BeginTransaction`](https://docs.aws.amazon.com/rdsdataservice/latest/APIReference/API_BeginTransaction.html) accepts only `resourceArn`, `secretArn`, `database`, and `schema` — there is no isolation parameter.
* The Data API pools backend connections opaquely. A `SET TRANSACTION ISOLATION LEVEL ...` sent as a separate `ExecuteStatement` before `BeginTransaction` has no guaranteed affinity to the backend session that the transaction will run on, so the setting is silently dropped.
* [Multi-statement SQL is not supported](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.troubleshooting.html), so `SET TRANSACTION ...; START TRANSACTION;` cannot be sent as a single call either.
* MySQL rejects `SET TRANSACTION ISOLATION LEVEL` inside an already-started transaction with [error 1568](https://dev.mysql.com/doc/refman/8.0/en/set-transaction.html), so the approach used for Aurora PostgreSQL (issuing `SET` as the first statement inside the started transaction) is not available on MySQL.

<!-- ZH -->
* [`BeginTransaction`](https://docs.aws.amazon.com/rdsdataservice/latest/APIReference/API_BeginTransaction.html) 只接受 `resourceArn`、`secretArn`、`database` 和 `schema`——没有隔离级别参数。
* Data API 以不透明的方式池化后端连接。在 `BeginTransaction` 之前作为单独一条 `ExecuteStatement` 发送的 `SET TRANSACTION ISOLATION LEVEL ...`，无法保证与该事务实际运行的后端会话亲和，因此该设置会被静默丢弃。
* [不支持多语句 SQL](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.troubleshooting.html)，所以 `SET TRANSACTION ...; START TRANSACTION;` 也无法作为单次调用发送。
* MySQL 会以[错误 1568](https://dev.mysql.com/doc/refman/8.0/en/set-transaction.html)拒绝在已开始的事务内部执行 `SET TRANSACTION ISOLATION LEVEL`，因此 Aurora PostgreSQL 所采用的做法（把 `SET` 作为已开启事务内的第一条语句发出）在 MySQL 上不可用。

<!-- EN -->
Aurora MySQL via the `mysql` driver

<!-- ZH -->
通过 `mysql` 驱动的 Aurora MySQL

<!-- EN -->
If per-transaction isolation levels are needed against an Aurora MySQL cluster, use the standard `mysql` driver pointed at the cluster writer endpoint instead of `aurora-mysql`. That path uses a regular MySQL protocol connection (via `mysql2`) and supports the full set of isolation levels listed above.

<!-- ZH -->
如果确实需要针对 Aurora MySQL 集群使用按事务的隔离级别，请改用指向集群写入端点的标准 `mysql` 驱动，而不是 `aurora-mysql`。该路径使用常规的 MySQL 协议连接（通过 `mysql2`），并支持上面列出的完整隔离级别集合。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [MySQL SET TRANSACTION](https://dev.mysql.com/doc/refman/8.0/en/set-transaction.html)

<!-- ZH -->
* [MySQL SET TRANSACTION](https://dev.mysql.com/doc/refman/8.0/en/set-transaction.html)

<!-- EN -->
### Oracle

<!-- ZH -->
### Oracle

<!-- EN -->
* `READ COMMITTED`
* `SERIALIZABLE`

<!-- ZH -->
* `READ COMMITTED`
* `SERIALIZABLE`

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Oracle Data Concurrency and Consistency](https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/data-concurrency-and-consistency.html)

<!-- ZH -->
* [Oracle Data Concurrency and Consistency](https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/data-concurrency-and-consistency.html)

<!-- EN -->
### PostgreSQL

<!-- ZH -->
### PostgreSQL

<!-- EN -->
* `READ UNCOMMITTED`
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`

<!-- ZH -->
* `READ UNCOMMITTED`
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`

<!-- EN -->
Aurora PostgreSQL

<!-- ZH -->
Aurora PostgreSQL

<!-- EN -->
The same set of isolation levels is supported by the `aurora-postgres` driver, which talks to Aurora PostgreSQL clusters through the RDS Data API.

<!-- ZH -->
`aurora-postgres` 驱动同样支持这一组隔离级别，它通过 RDS Data API 与 Aurora PostgreSQL 集群通信。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [PostgreSQL Transaction Isolation](https://www.postgresql.org/docs/current/transaction-iso.html)

<!-- ZH -->
* [PostgreSQL Transaction Isolation](https://www.postgresql.org/docs/current/transaction-iso.html)

<!-- EN -->
### SAP HANA

<!-- ZH -->
### SAP HANA

<!-- EN -->
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`

<!-- ZH -->
* `READ COMMITTED`
* `REPEATABLE READ`
* `SERIALIZABLE`

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [SAP HANA Transaction Isolation Levels](https://help.sap.com/docs/SAP_HANA_PLATFORM/4fe29514fd584807ac9f2a04f6754767/5e7cb20c7b8c44a19cc61c64ca4fcb3b.html)

<!-- ZH -->
* [SAP HANA Transaction Isolation Levels](https://help.sap.com/docs/SAP_HANA_PLATFORM/4fe29514fd584807ac9f2a04f6754767/5e7cb20c7b8c44a19cc61c64ca4fcb3b.html)

<!-- EN -->
### SQLite

<!-- ZH -->
### SQLite

<!-- EN -->
* `READ UNCOMMITTED` — only takes effect when [shared-cache mode](https://www.sqlite.org/sharedcache.html) is enabled; in the default mode SQLite always uses `SERIALIZABLE` regardless
* `SERIALIZABLE`

<!-- ZH -->
* `READ UNCOMMITTED` —— 只有在启用[共享缓存模式](https://www.sqlite.org/sharedcache.html)时才生效；在默认模式下 SQLite 始终使用 `SERIALIZABLE`
* `SERIALIZABLE`

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [SQLite Isolation](https://www.sqlite.org/isolation.html)

<!-- ZH -->
* [SQLite Isolation](https://www.sqlite.org/isolation.html)

<!-- EN -->
## Default isolation level

<!-- ZH -->
## 默认隔离级别

<!-- EN -->
You can configure a default isolation level for all transactions by setting `isolationLevel` in the DataSource options:

<!-- ZH -->
你可以通过在 DataSource 选项中设置 `isolationLevel`，为所有事务配置默认隔离级别：

<!-- EN -->
```typescript
const dataSource = new DataSource({
    type: "postgres",
    isolationLevel: "SERIALIZABLE",
    // ...
})
```

<!-- ZH -->
```typescript
const dataSource = new DataSource({
    type: "postgres",
    isolationLevel: "SERIALIZABLE",
    // ...
})
```

<!-- EN -->
When set, all transactions started without an explicit isolation level will use this default. An explicit isolation level passed to `transaction()` or `startTransaction()` will override the default.

<!-- ZH -->
设置后，所有未显式指定隔离级别就启动的事务都会使用该默认值。传给 `transaction()` 或 `startTransaction()` 的显式隔离级别会覆盖默认值。

<!-- EN -->
## Using `QueryRunner` to create and control state of single database connection

<!-- ZH -->
## 用 `QueryRunner` 创建并控制单个数据库连接的状态

<!-- EN -->
`QueryRunner` provides a single database connection. Transactions are organized using query runners. Single transactions can only be established on a single query runner. You can manually create a query runner instance and use it to manually control transaction state. Example:

<!-- ZH -->
`QueryRunner` 提供单个数据库连接。事务是借助 query runner 组织起来的。单个事务只能建立在单个 query runner 上。你可以手动创建 query runner 实例，并用它手动控制事务状态。示例：

<!-- EN -->
```typescript
// create a new query runner
const queryRunner = dataSource.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 users")

// we can also access entity manager that works with connection created by a query runner:
const users = await queryRunner.manager.find(User)

// lets now open a new transaction:
await queryRunner.startTransaction()

try {
    // execute some operations on this transaction:
    await queryRunner.manager.save(user1)
    await queryRunner.manager.save(user2)
    await queryRunner.manager.save(photos)

    // commit transaction now:
    await queryRunner.commitTransaction()
} catch (err) {
    // since we have errors let's rollback changes we made
    await queryRunner.rollbackTransaction()
} finally {
    // you need to release query runner which is manually created:
    await queryRunner.release()
}
```

<!-- ZH -->
```typescript
// 创建一个新的 query runner
const queryRunner = dataSource.createQueryRunner()

// 用我们新建的 query runner 建立真实的数据库连接
await queryRunner.connect()

// 现在我们可以在 query runner 上执行任何查询，例如：
await queryRunner.query("SELECT * FROM users")

// 我们也可以访问与该 query runner 所创建连接协同工作的 entity manager：
const users = await queryRunner.manager.find(User)

// 现在开启一个新事务：
await queryRunner.startTransaction()

try {
    // 在该事务上执行一些操作：
    await queryRunner.manager.save(user1)
    await queryRunner.manager.save(user2)
    await queryRunner.manager.save(photos)

    // 现在提交事务：
    await queryRunner.commitTransaction()
} catch (err) {
    // 既然出错了，就回滚我们所做的改动
    await queryRunner.rollbackTransaction()
} finally {
    // 你需要释放手动创建的 query runner：
    await queryRunner.release()
}
```

<!-- EN -->
There are 3 methods to control transactions in `QueryRunner`:

<!-- ZH -->
`QueryRunner` 中有 3 个控制事务的方法：

<!-- EN -->
* `startTransaction` - starts a new transaction inside the query runner instance.
* `commitTransaction` - commits all changes made using the query runner instance.
* `rollbackTransaction` - rolls all changes made using the query runner instance back.

<!-- ZH -->
* `startTransaction` - 在该 query runner 实例内部开启一个新事务。
* `commitTransaction` - 提交使用该 query runner 实例所做的所有改动。
* `rollbackTransaction` - 回滚使用该 query runner 实例所做的所有改动。

<!-- EN -->
Learn more about [Query Runner](https://typeorm.io/docs/query-runner).

<!-- ZH -->
进一步了解 [Query Runner](https://typeorm.io/docs/query-runner)。
