# EntityManager API

> 英文标题：EntityManager API
> 官网原文：https://typeorm.io/docs/working-with-entity-manager/entity-manager-api
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 89 块

---

<!-- EN -->
# `EntityManager` API

<!-- ZH -->
# `EntityManager` API

<!-- EN -->
* `dataSource` - The DataSource used by `EntityManager`.

<!-- ZH -->
* `dataSource` - `EntityManager` 所使用的 DataSource。

<!-- EN -->
```typescript
const dataSource = manager.dataSource
```

<!-- ZH -->
```typescript
const dataSource = manager.dataSource
```

<!-- EN -->
* `queryRunner` - The query runner used by `EntityManager`. Used only in transactional instances of EntityManager.

<!-- ZH -->
* `queryRunner` - `EntityManager` 所使用的 query runner。仅在 EntityManager 的事务型实例中使用。

<!-- EN -->
```typescript
const queryRunner = manager.queryRunner
```

<!-- ZH -->
```typescript
const queryRunner = manager.queryRunner
```

<!-- EN -->
* `transaction` - Provides a transaction where multiple database requests will be executed in a single database transaction. Learn more [Transactions](https://typeorm.io/docs/transactions).

<!-- ZH -->
* `transaction` - 提供一个事务，在其中多个数据库请求会在同一个数据库事务中执行。进一步了解[事务](https://typeorm.io/docs/transactions)。

<!-- EN -->
```typescript
await manager.transaction(async (manager) => {
    // NOTE: you must perform all database operations using the given manager instance
    // it's a special instance of EntityManager working with this transaction
    // and don't forget to await things here
})
```

<!-- ZH -->
```typescript
await manager.transaction(async (manager) => {
    // 注意：你必须使用给定的 manager 实例执行所有数据库操作
    // 它是一个与该事务协同工作的特殊 EntityManager 实例
    // 并且别忘了在这里 await 各个操作
})
```

<!-- EN -->
* `query` - Executes a raw SQL query.

<!-- ZH -->
* `query` - 执行一条原生 SQL 查询。

<!-- EN -->
```typescript
const rawData = await manager.query(`SELECT * FROM USERS`)

// You can also use parameters to avoid SQL injection
// The syntax differs between the drivers

// aurora-mysql, better-sqlite3, capacitor, cordova,
// expo, mariadb, mysql, nativescript, react-native,
// sap, sqlite, sqljs
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = ? and age = ?",
    ["John", 24],
)

// aurora-postgres, cockroachdb, postgres
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = $1 and age = $2",
    ["John", 24],
)

// oracle
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = :1 and age = :2",
    ["John", 24],
)

// spanner
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = @param0 and age = @param1",
    ["John", 24],
)

// mssql
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = @0 and age = @1",
    ["John", 24],
)
```

<!-- ZH -->
```typescript
const rawData = await manager.query(`SELECT * FROM USERS`)

// 你也可以使用参数来避免 SQL 注入
// 不同驱动的语法有所不同

// aurora-mysql, better-sqlite3, capacitor, cordova,
// expo, mariadb, mysql, nativescript, react-native,
// sap, sqlite, sqljs
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = ? and age = ?",
    ["John", 24],
)

// aurora-postgres, cockroachdb, postgres
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = $1 and age = $2",
    ["John", 24],
)

// oracle
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = :1 and age = :2",
    ["John", 24],
)

// spanner
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = @param0 and age = @param1",
    ["John", 24],
)

// mssql
const rawData = await manager.query(
    "SELECT * FROM USERS WHERE name = @0 and age = @1",
    ["John", 24],
)
```

<!-- EN -->
* `sql` - Executes a raw SQL query using template literals.

<!-- ZH -->
* `sql` - 使用模板字符串执行一条原生 SQL 查询。

<!-- EN -->
```typescript
const rawData =
    await manager.sql`SELECT * FROM USERS WHERE name = ${"John"} and age = ${24}`
```

<!-- ZH -->
```typescript
const rawData =
    await manager.sql`SELECT * FROM USERS WHERE name = ${"John"} and age = ${24}`
```

<!-- EN -->
Learn more about using the [SQL Tag syntax](https://typeorm.io/docs/guides/sql-tag).

<!-- ZH -->
进一步了解 [SQL 标签语法](https://typeorm.io/docs/guides/sql-tag)的用法。

<!-- EN -->
* `createQueryBuilder` - Creates a query builder use to build SQL queries. Learn more about [QueryBuilder](https://typeorm.io/docs/query-builder/select-query-builder).

<!-- ZH -->
* `createQueryBuilder` - 创建一个用于构建 SQL 查询的 query builder。进一步了解 [QueryBuilder](https://typeorm.io/docs/query-builder/select-query-builder)。

<!-- EN -->
```typescript
const users = await manager
    .createQueryBuilder()
    .select()
    .from(User, "user")
    .where("user.name = :name", { name: "John" })
    .getMany()
```

<!-- ZH -->
```typescript
const users = await manager
    .createQueryBuilder()
    .select()
    .from(User, "user")
    .where("user.name = :name", { name: "John" })
    .getMany()
```

<!-- EN -->
* `hasId` - Checks if given entity has its primary column property defined.

<!-- ZH -->
* `hasId` - 检查给定实体是否已定义其主键列属性。

<!-- EN -->
```typescript
if (manager.hasId(user)) {
    // ... do something
}
```

<!-- ZH -->
```typescript
if (manager.hasId(user)) {
    // ... 做点什么
}
```

<!-- EN -->
* `getId` - Gets given entity's primary column property value. If the entity has composite primary keys then the returned value will be an object with names and values of primary columns.

<!-- ZH -->
* `getId` - 获取给定实体的主键列属性值。如果该实体有复合主键，返回值将是一个包含主键列名称与值的对象。

<!-- EN -->
```typescript
const userId = manager.getId(user) // userId === 1
```

<!-- ZH -->
```typescript
const userId = manager.getId(user) // userId === 1
```

<!-- EN -->
* `create` - Creates a new instance of `User`. Optionally accepts an object literal with user properties which will be written into newly created user object.

<!-- ZH -->
* `create` - 创建一个新的 `User` 实例。可选地接受一个带用户属性的对象字面量，这些属性会被写入新建的 user 对象。

<!-- EN -->
```typescript
const user = manager.create(User) // same as const user = new User();
const user = manager.create(User, {
    id: 1,
    firstName: "Timber",
    lastName: "Saw",
}) // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
```

<!-- ZH -->
```typescript
const user = manager.create(User) // 等同于 const user = new User();
const user = manager.create(User, {
    id: 1,
    firstName: "Timber",
    lastName: "Saw",
}) // 等同于 const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
```

<!-- EN -->
* `merge` - Merges multiple entities into a single entity.

<!-- ZH -->
* `merge` - 把多个实体合并进单个实体。

<!-- EN -->
```typescript
const user = new User()
manager.merge(User, user, { firstName: "Timber" }, { lastName: "Saw" }) // same as user.firstName = "Timber"; user.lastName = "Saw";
```

<!-- ZH -->
```typescript
const user = new User()
manager.merge(User, user, { firstName: "Timber" }, { lastName: "Saw" }) // 等同于 user.firstName = "Timber"; user.lastName = "Saw";
```

<!-- EN -->
* `preload` - Creates a new entity from the given plain javascript object. If the entity already exist in the database, then it loads it (and everything related to it), replaces all values with the new ones from the given object, and returns the new entity. The new entity is actually loaded from the database entity with all properties replaced from the new object.

<!-- ZH -->
* `preload` - 从给定的普通 javascript 对象创建一个新实体。如果该实体已存在于数据库中，它会加载它（以及与之相关的一切），用给定对象中的新值替换所有值，并返回这个新实体。这个新实体实际上是从数据库实体加载而来、其所有属性都被新对象替换后的结果。

<!-- EN -->
```typescript
const partialUser = {
    id: 1,
    firstName: "Rizzrak",
    profile: {
        id: 1,
    },
}
const user = await manager.preload(User, partialUser)
// user will contain all missing data from partialUser with partialUser property values:
// { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } }
```

<!-- ZH -->
```typescript
const partialUser = {
    id: 1,
    firstName: "Rizzrak",
    profile: {
        id: 1,
    },
}
const user = await manager.preload(User, partialUser)
// user 会包含 partialUser 中缺失的所有数据，其中属性值来自 partialUser：
// { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } }
```

<!-- EN -->
* `save` - Saves a given entity or array of entities. If the entity already exists in the database, then it's updated. If the entity does not exist in the database yet, it's inserted. It saves all given entities in a single transaction (in the case of entity manager is not transactional). Also supports partial updating since all undefined properties are skipped. In order to make a value `NULL`, you must manually set the property to equal `null`.

<!-- ZH -->
* `save` - 保存给定实体或实体数组。如果实体已存在于数据库中，则更新它。如果实体尚不存在于数据库中，则插入它。它会在单个事务中保存所有给定实体（在 entity manager 本身不是事务型的情况下）。也支持部分更新，因为所有值为 undefined 的属性都会被跳过。要把某个值设为 `NULL`，你必须手动把该属性设为 `null`。

<!-- EN -->
```typescript
await manager.save(user)
await manager.save([category1, category2, category3])
```

<!-- ZH -->
```typescript
await manager.save(user)
await manager.save([category1, category2, category3])
```

<!-- EN -->
* `remove` - Removes a given entity or array of entities. It removes all given entities in a single transaction (in the case of entity, manager is not transactional).

<!-- ZH -->
* `remove` - 移除给定实体或实体数组。它会在单个事务中移除所有给定实体（在 entity manager 本身不是事务型的情况下）。

<!-- EN -->
```typescript
await manager.remove(user)
await manager.remove([category1, category2, category3])
```

<!-- ZH -->
```typescript
await manager.remove(user)
await manager.remove([category1, category2, category3])
```

<!-- EN -->
* `insert` - Inserts a new entity, or array of entities.

<!-- ZH -->
* `insert` - 插入一个新实体或实体数组。

<!-- EN -->
```typescript
await manager.insert(User, {
    firstName: "Timber",
    lastName: "Timber",
})

await manager.insert(User, [
    {
        firstName: "Foo",
        lastName: "Bar",
    },
    {
        firstName: "Rizz",
        lastName: "Rak",
    },
])
```

<!-- ZH -->
```typescript
await manager.insert(User, {
    firstName: "Timber",
    lastName: "Timber",
})

await manager.insert(User, [
    {
        firstName: "Foo",
        lastName: "Bar",
    },
    {
        firstName: "Rizz",
        lastName: "Rak",
    },
])
```

<!-- EN -->
* `update` - Updates entities by entity id, ids, given conditions, or an array of condition objects. Sets fields from supplied partial entity.

<!-- ZH -->
* `update` - 按实体 id、多个 id、给定条件或条件对象数组更新实体。用提供的部分实体设置字段。

<!-- EN -->
```typescript
await manager.update(User, { age: 18 }, { category: "ADULT" })
// executes UPDATE user SET category = ADULT WHERE age = 18

await manager.update(User, 1, { firstName: "Rizzrak" })
// executes UPDATE user SET firstName = Rizzrak WHERE id = 1
```

<!-- ZH -->
```typescript
await manager.update(User, { age: 18 }, { category: "ADULT" })
// 执行 UPDATE user SET category = ADULT WHERE age = 18

await manager.update(User, 1, { firstName: "Rizzrak" })
// 执行 UPDATE user SET firstName = Rizzrak WHERE id = 1
```

<!-- EN -->
You can pass an **array of condition objects** to match multiple distinct sets of rows in a single call (conditions are OR'd together):

<!-- ZH -->
你可以传入一个**条件对象数组**，在一次调用中匹配多组不同的行（各条件之间是 OR 关系）：

<!-- EN -->
```typescript
await manager.update(User, [{ status: "expired" }, { flagged: true }], {
    active: false,
})
// executes UPDATE user SET active = false WHERE status = 'expired' OR flagged = true
```

<!-- ZH -->
```typescript
await manager.update(User, [{ status: "expired" }, { flagged: true }], {
    active: false,
})
// 执行 UPDATE user SET active = false WHERE status = 'expired' OR flagged = true
```

<!-- EN -->
* `updateAll` - Updates *all* entities of target type (without WHERE clause). Sets fields from supplied partial entity.

<!-- ZH -->
* `updateAll` - 更新目标类型的*所有*实体（不带 WHERE 子句）。用提供的部分实体设置字段。

<!-- EN -->
```typescript
await manager.updateAll(User, { category: "ADULT" })
// executes UPDATE user SET category = ADULT
```

<!-- ZH -->
```typescript
await manager.updateAll(User, { category: "ADULT" })
// 执行 UPDATE user SET category = ADULT
```

<!-- EN -->
* `upsert` - Inserts a new entity or array of entities unless they already exist in which case they are updated instead. Supported by AuroraDataApi, Cockroach, Mysql, Postgres, and Sqlite database drivers.

<!-- ZH -->
* `upsert` - 插入一个新实体或实体数组；如果它们已存在，则改为更新。受 AuroraDataApi、Cockroach、Mysql、Postgres 和 Sqlite 数据库驱动支持。

<!-- EN -->
When an upsert operation results in an update (due to a conflict), special columns like `@UpdateDateColumn` and `@VersionColumn` are automatically updated to their current values.

<!-- ZH -->
当 upsert 操作因冲突而变成更新时，`@UpdateDateColumn` 和 `@VersionColumn` 这类特殊列会被自动更新为当前值。

<!-- EN -->
Columns marked with `update: false` or defined as computed generated columns (via `asExpression`/`generatedType`) are **never** included in the update set on conflict. If all non-conflict columns are excluded by these rules (i.e. there are no updatable columns), the upsert degrades to an insert-or-ignore operation and the existing row is left completely unchanged. On databases that support conflict targets (e.g. PostgreSQL, CockroachDB), this is scoped to the specified conflict columns; on MySQL-family databases, `INSERT IGNORE` is used which applies to all unique constraints.

<!-- ZH -->
用 `update: false` 标记的列，或被定义为计算生成列（通过 `asExpression`/`generatedType`）的列，**永远不会**被包含在冲突时的更新集合中。如果所有非冲突列都被这些规则排除（即没有可更新的列），该 upsert 会降级为"插入或忽略"操作，已存在的行保持完全不变。在支持冲突目标的数据库上（例如 PostgreSQL、CockroachDB），这限定在所指定的冲突列范围内；在 MySQL 系数据库上，使用的是 `INSERT IGNORE`，它对所有唯一约束生效。

<!-- EN -->
```typescript
await manager.upsert(
    User,
    [
        { externalId: "abc123", firstName: "Rizzrak" },
        { externalId: "bca321", firstName: "Karzzir" },
    ],
    ["externalId"],
)
/** executes
 *  INSERT INTO user
 *  VALUES
 *      (externalId = abc123, firstName = Rizzrak),
 *      (externalId = cba321, firstName = Karzzir),
 *  ON CONFLICT (externalId) DO UPDATE firstName = EXCLUDED.firstName
 **/
```

<!-- ZH -->
```typescript
await manager.upsert(
    User,
    [
        { externalId: "abc123", firstName: "Rizzrak" },
        { externalId: "bca321", firstName: "Karzzir" },
    ],
    ["externalId"],
)
/** 执行
 *  INSERT INTO user
 *  VALUES
 *      (externalId = abc123, firstName = Rizzrak),
 *      (externalId = cba321, firstName = Karzzir),
 *  ON CONFLICT (externalId) DO UPDATE firstName = EXCLUDED.firstName
 **/
```

<!-- EN -->
* `delete` - Deletes entities by entity id, ids, given conditions, or an array of condition objects.

<!-- ZH -->
* `delete` - 按实体 id、多个 id、给定条件或条件对象数组删除实体。

<!-- EN -->
```typescript
await manager.delete(User, 1)
await manager.delete(User, [1, 2, 3])
await manager.delete(User, { firstName: "Timber" })

// An array of condition objects is OR'd into one query
await manager.delete(User, [{ firstName: "Timber" }, { age: 18 }, { id: 42 }])
// executes DELETE FROM user WHERE firstName = Timber OR age = 18 OR id = 42
```

<!-- ZH -->
```typescript
await manager.delete(User, 1)
await manager.delete(User, [1, 2, 3])
await manager.delete(User, { firstName: "Timber" })

// 条件对象数组会被 OR 组合成一条查询
await manager.delete(User, [{ firstName: "Timber" }, { age: 18 }, { id: 42 }])
// 执行 DELETE FROM user WHERE firstName = Timber OR age = 18 OR id = 42
```

<!-- EN -->
You can pass an **array of condition objects** to match multiple distinct sets of rows in a single call (conditions are OR'd together). This is different from passing a primitive array, which is treated as a list of IDs:

<!-- ZH -->
你可以传入一个**条件对象数组**，在一次调用中匹配多组不同的行（各条件之间是 OR 关系）。这与传入原始类型数组不同，后者会被当作 ID 列表处理：

<!-- EN -->
```typescript
// Primitive array — interpreted as WHERE id IN (1, 2, 3)
await manager.delete(User, [1, 2, 3])

// Object array — each element is a separate condition (OR'd together)
await manager.delete(User, [{ id: 1 }, { email: "[email protected]" }])
// executes DELETE FROM user WHERE id = 1 OR email = '[email protected]'
```

<!-- ZH -->
```typescript
// 原始类型数组——被解释为 WHERE id IN (1, 2, 3)
await manager.delete(User, [1, 2, 3])

// 对象数组——每个元素都是一个独立条件（彼此 OR）
await manager.delete(User, [{ id: 1 }, { email: "[email protected]" }])
// 执行 DELETE FROM user WHERE id = 1 OR email = '[email protected]'
```

<!-- EN -->
Note: passing an empty object `{}` or `[{}]` throws a `TypeORMError` to prevent accidental full-table deletes.

<!-- ZH -->
注意：传入空对象 `{}` 或 `[{}]` 会抛出 `TypeORMError`，以防止意外删除整张表。

<!-- EN -->
* `deleteAll` - Deletes *all* entities of target type (without WHERE clause).

<!-- ZH -->
* `deleteAll` - 删除目标类型的*所有*实体（不带 WHERE 子句）。

<!-- EN -->
```typescript
await manager.deleteAll(User)
// executes DELETE FROM user
```

<!-- ZH -->
```typescript
await manager.deleteAll(User)
// 执行 DELETE FROM user
```

<!-- EN -->
Refer also to the `clear` method, which performs database `TRUNCATE TABLE` operation instead.

<!-- ZH -->
另请参阅 `clear` 方法，它执行的是数据库的 `TRUNCATE TABLE` 操作。

<!-- EN -->
* `increment` - Increments some column by provided value of entities that match given options.

<!-- ZH -->
* `increment` - 把匹配给定选项的实体的某个列增加指定值。

<!-- EN -->
```typescript
await manager.increment(User, { firstName: "Timber" }, "age", 3)
```

<!-- ZH -->
```typescript
await manager.increment(User, { firstName: "Timber" }, "age", 3)
```

<!-- EN -->
* `decrement` - Decrements some column by provided value that match given options.

<!-- ZH -->
* `decrement` - 把匹配给定选项的某个列减少指定值。

<!-- EN -->
```typescript
await manager.decrement(User, { firstName: "Timber" }, "age", 3)
```

<!-- ZH -->
```typescript
await manager.decrement(User, { firstName: "Timber" }, "age", 3)
```

<!-- EN -->
* `exists` - Check whether any entity exists that matches `FindOptions`.

<!-- ZH -->
* `exists` - 检查是否存在匹配 `FindOptions` 的实体。

<!-- EN -->
```typescript
const exists = await manager.exists(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const exists = await manager.exists(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `existsBy` - Checks whether any entity exists that matches `FindOptionsWhere`.

<!-- ZH -->
* `existsBy` - 检查是否存在匹配 `FindOptionsWhere` 的实体。

<!-- EN -->
```typescript
const exists = await manager.existsBy(User, { firstName: "Timber" })
```

<!-- ZH -->
```typescript
const exists = await manager.existsBy(User, { firstName: "Timber" })
```

<!-- EN -->
* `count` - Counts entities that match `FindOptions`. Useful for pagination.

<!-- ZH -->
* `count` - 统计匹配 `FindOptions` 的实体数量。对分页很有用。

<!-- EN -->
```typescript
const count = await manager.count(User, {
    where: {
        firstName: "Timber",
    },
})

const distinctCount = await manager.count(User, {
    select: {
        firstName: true,
    },
})
```

<!-- ZH -->
```typescript
const count = await manager.count(User, {
    where: {
        firstName: "Timber",
    },
})

const distinctCount = await manager.count(User, {
    select: {
        firstName: true,
    },
})
```

<!-- EN -->
When `select` is provided, counts distinct combinations of selected columns, including selected relation columns when paired with `relations`. If `select` is not provided, default count behavior is unchanged.

<!-- ZH -->
提供了 `select` 时，统计的是所选列的不同组合数量；当与 `relations` 搭配时，也包含所选的关系列。如果未提供 `select`，默认计数行为不变。

<!-- EN -->
* `countBy` - Counts entities that match `FindOptionsWhere`. Useful for pagination.

<!-- ZH -->
* `countBy` - 统计匹配 `FindOptionsWhere` 的实体数量。对分页很有用。

<!-- EN -->
```typescript
const count = await manager.countBy(User, { firstName: "Timber" })
```

<!-- ZH -->
```typescript
const count = await manager.countBy(User, { firstName: "Timber" })
```

<!-- EN -->
* `find` - Finds entities that match given `FindOptions`.

<!-- ZH -->
* `find` - 查找匹配给定 `FindOptions` 的实体。

<!-- EN -->
```typescript
const timbers = await manager.find(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const timbers = await manager.find(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `findBy` - Finds entities that match given `FindWhereOptions`.

<!-- ZH -->
* `findBy` - 查找匹配给定 `FindWhereOptions` 的实体。

<!-- EN -->
```typescript
const timbers = await manager.findBy(User, {
    firstName: "Timber",
})
```

<!-- ZH -->
```typescript
const timbers = await manager.findBy(User, {
    firstName: "Timber",
})
```

<!-- EN -->
* `findAndCount` - Finds entities that match given `FindOptions`. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).

<!-- ZH -->
* `findAndCount` - 查找匹配给定 `FindOptions` 的实体。同时统计匹配给定条件的所有实体数量，但会忽略分页设置（from 和 take 选项）。

<!-- EN -->
```typescript
const [timbers, timbersCount] = await manager.findAndCount(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const [timbers, timbersCount] = await manager.findAndCount(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `findAndCountBy` - Finds entities that match given `FindOptionsWhere`. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).

<!-- ZH -->
* `findAndCountBy` - 查找匹配给定 `FindOptionsWhere` 的实体。同时统计匹配给定条件的所有实体数量，但会忽略分页设置（from 和 take 选项）。

<!-- EN -->
```typescript
const [timbers, timbersCount] = await manager.findAndCountBy(User, {
    firstName: "Timber",
})
```

<!-- ZH -->
```typescript
const [timbers, timbersCount] = await manager.findAndCountBy(User, {
    firstName: "Timber",
})
```

<!-- EN -->
* `findOne` - Finds the first entity that matches given `FindOptions`.

<!-- ZH -->
* `findOne` - 查找匹配给定 `FindOptions` 的第一个实体。

<!-- EN -->
```typescript
const timber = await manager.findOne(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const timber = await manager.findOne(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `findOneBy` - Finds the first entity that matches given `FindOptionsWhere`.

<!-- ZH -->
* `findOneBy` - 查找匹配给定 `FindOptionsWhere` 的第一个实体。

<!-- EN -->
```typescript
const timber = await manager.findOneBy(User, { firstName: "Timber" })
```

<!-- ZH -->
```typescript
const timber = await manager.findOneBy(User, { firstName: "Timber" })
```

<!-- EN -->
* `findOneOrFail` - Finds the first entity that matches some id or find options. Rejects the returned promise if nothing matches.

<!-- ZH -->
* `findOneOrFail` - 查找匹配某个 id 或查找选项的第一个实体。如果没有匹配项，返回的 promise 会被拒绝。

<!-- EN -->
```typescript
const timber = await manager.findOneOrFail(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const timber = await manager.findOneOrFail(User, {
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `findOneByOrFail` - Finds the first entity that matches given `FindOptions`. Rejects the returned promise if nothing matches.

<!-- ZH -->
* `findOneByOrFail` - 查找匹配给定 `FindOptions` 的第一个实体。如果没有匹配项，返回的 promise 会被拒绝。

<!-- EN -->
```typescript
const timber = await manager.findOneByOrFail(User, { firstName: "Timber" })
```

<!-- ZH -->
```typescript
const timber = await manager.findOneByOrFail(User, { firstName: "Timber" })
```

<!-- EN -->
* `clear` - Clears all the data from (truncates) the given table. Supports cascade option to also clear all the data from the tables that have foreign keys to this table (supported by PostgreSQL/CockroachDB and Oracle only; other databases throw an error if cascade option is set to true).

<!-- ZH -->
* `clear` - 清空（截断）给定表中的所有数据。支持 cascade 选项，可同时清空带有指向该表外键的表中的所有数据（仅 PostgreSQL/CockroachDB 和 Oracle 支持；其他数据库在 cascade 选项设为 true 时会抛出错误）。

<!-- EN -->
```typescript
await manager.clear(User)

// With cascade option (PostgreSQL/CockroachDB and Oracle only)
await manager.clear(User, { cascade: true })
```

<!-- ZH -->
```typescript
await manager.clear(User)

// 带 cascade 选项（仅 PostgreSQL/CockroachDB 和 Oracle）
await manager.clear(User, { cascade: true })
```

<!-- EN -->
* `getRepository` - Gets `Repository` to perform operations on a specific entity. Learn more about [Repositories](https://typeorm.io/docs/working-with-entity-manager/working-with-repository).

<!-- ZH -->
* `getRepository` - 获取用于对特定实体执行操作的 `Repository`。进一步了解 [Repository](https://typeorm.io/docs/working-with-entity-manager/working-with-repository)。

<!-- EN -->
```typescript
const userRepository = manager.getRepository(User)
```

<!-- ZH -->
```typescript
const userRepository = manager.getRepository(User)
```

<!-- EN -->
* `getTreeRepository` - Gets `TreeRepository` to perform operations on a specific entity. Learn more about [Repositories](https://typeorm.io/docs/working-with-entity-manager/working-with-repository).

<!-- ZH -->
* `getTreeRepository` - 获取用于对特定实体执行操作的 `TreeRepository`。进一步了解 [Repository](https://typeorm.io/docs/working-with-entity-manager/working-with-repository)。

<!-- EN -->
```typescript
const categoryRepository = manager.getTreeRepository(Category)
```

<!-- ZH -->
```typescript
const categoryRepository = manager.getTreeRepository(Category)
```

<!-- EN -->
* `getMongoRepository` - Gets `MongoRepository` to perform operations on a specific entity. Learn more about [MongoDB](https://typeorm.io/docs/drivers/mongodb).

<!-- ZH -->
* `getMongoRepository` - 获取用于对特定实体执行操作的 `MongoRepository`。进一步了解 [MongoDB](https://typeorm.io/docs/drivers/mongodb)。

<!-- EN -->
```typescript
const userRepository = manager.getMongoRepository(User)
```

<!-- ZH -->
```typescript
const userRepository = manager.getMongoRepository(User)
```

<!-- EN -->
* `withRepository` - Gets custom repository instance used in a transaction. Learn more about [Custom repositories](https://typeorm.io/docs/working-with-entity-manager/custom-repository).

<!-- ZH -->
* `withRepository` - 获取在事务中使用的自定义 repository 实例。进一步了解[自定义仓储](https://typeorm.io/docs/working-with-entity-manager/custom-repository)。

<!-- EN -->
```typescript
const myUserRepository = manager.withRepository(UserRepository)
```

<!-- ZH -->
```typescript
const myUserRepository = manager.withRepository(UserRepository)
```

<!-- EN -->
* `release` - Releases query runner of an entity manager. Used only when query runner was created and managed manually.

<!-- ZH -->
* `release` - 释放 entity manager 的 query runner。仅在 query runner 是手动创建并管理时使用。

<!-- EN -->
```typescript
await manager.release()
```

<!-- ZH -->
```typescript
await manager.release()
```
