# Entity Manager API

* `connection` - The connection used by `EntityManager`.

```typescript
const connection = manager.connection;
```

* `queryRunner` - The query runner used by `EntityManager`.

  Used only in transactional instances of EntityManager.

```typescript
const queryRunner = manager.queryRunner;
```

* `transaction` - Provides a transaction where multiple database requests will be executed in a single database transaction.

  Learn more [Transactions](https://app.gitbook.com/s/-MJXhrMo66fLGmJ5EzAL/entity-manager-and-repository/transactions.md).

```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
});
```

* `query` - Executes a raw SQL query.

```typescript
const rawData = await manager.query(`SELECT * FROM USERS`);
```

* `createQueryBuilder` - Creates a query builder use to build SQL queries.

  Learn more about [QueryBuilder](https://app.gitbook.com/s/-MJXhrMo66fLGmJ5EzAL/entity-manager-and-repository/select-query-builder.md).

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

* `hasId` - Checks if given entity has its primary column property defined.

```typescript
 if (manager.hasId(user)) {
    // ... do something
 }
```

* `getId` - Gets given entity's primary column property value.&#x20;

  If the entity has composite primary keys then the returned value will be an object with names and values of primary columns.

```typescript
const userId = manager.getId(user); // userId === 1
```

* `create` - Creates a new instance of `User`. Optionally accepts an object literal with user properties

  which will be written into newly created user object.

```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";
```

* `merge` - Merges multiple entities into a single entity.

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

* `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.

```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, ... } }
```

* `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`.

```typescript
await manager.save(user);
await manager.save([
    category1,
    category2,
    category3
]);
```

* `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).

```typescript
await manager.remove(user);
await manager.remove([
    category1,
    category2,
    category3
]);
```

* `insert` - Inserts a new entity, or array of entities.

```typescript
await manager.insert(User, { 
    firstName: "Timber", 
    lastName: "Timber" 
});

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

* `update` - Partially updates entity by a given update options or entity id.

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

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

* `delete` - Deletes entities by entity id, ids or given conditions:

```typescript
await manager.delete(User, 1);
await manager.delete(User, [1, 2, 3]);
await manager.delete(User, { firstName: "Timber" });
```

* `count` - Counts entities that match given options. Useful for pagination.

```typescript
const count = await manager.count(User, { firstName: "Timber" });
```

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

```typescript
await manager.increment(User, { firstName: "Timber" }, "age", 3);
```

* `decrement` - Decrements some column by provided value that match given options.

  ```typescript
  await manager.decrement(User, { firstName: "Timber" }, "age", 3);
  ```
* `find` - Finds entities that match given options.

```typescript
const timbers = await manager.find(User, { firstName: "Timber" });
```

* `findAndCount` - Finds entities that match given find options.

  Also counts all entities that match given conditions,

  but ignores pagination settings (from and take options).

```typescript
const [timbers, timbersCount] = await manager.findAndCount(User, { firstName: "Timber" });
```

* `findByIds` - Finds multiple entities by id.

```typescript
const users = await manager.findByIds(User, [1, 2, 3]);
```

* `findOne` - Finds the first entity that matches some id or find options.

```typescript
const user = await manager.findOne(User, 1);
const timber = await manager.findOne(User, { firstName: "Timber" });
```

* `findOneOrFail` - Finds the first entity that matches some id or find options.

  Rejects the returned promise if nothing matches.

```typescript
const user = await manager.findOneOrFail(User, 1);
const timber = await manager.findOneOrFail(User, { firstName: "Timber" });
```

* `clear` - Clears all the data from the given table (truncates/drops it).

```typescript
await manager.clear(User);
```

* `getRepository` - Gets `Repository` to perform operations on a specific entity.

  Learn more about [Repositories](https://app.gitbook.com/s/-MJXhrMo66fLGmJ5EzAL/entity-manager-and-repository/working-with-repository.md).

```typescript
const userRepository = manager.getRepository(User);
```

* `getTreeRepository` - Gets `TreeRepository` to perform operations on a specific entity.

  Learn more about [Repositories](https://app.gitbook.com/s/-MJXhrMo66fLGmJ5EzAL/entity-manager-and-repository/working-with-repository.md).

```typescript
const categoryRepository = manager.getTreeRepository(Category);
```

* `getMongoRepository` - Gets `MongoRepository` to perform operations on a specific entity.

  Learn more about [MongoDB](https://app.gitbook.com/s/-MJXhrMo66fLGmJ5EzAL/entity-manager-and-repository/mongodb.md).

```typescript
const userRepository = manager.getMongoRepository(User);
```

* `getCustomRepository` - Gets custom entity repository.

  Learn more about [Custom repositories](https://app.gitbook.com/s/-MJXhrMo66fLGmJ5EzAL/entity-manager-and-repository/custom-repository.md).

```typescript
const myUserRepository = manager.getCustomRepository(UserRepository);
```

* `release` - Releases query runner of an entity manager.&#x20;

  Used only when query runner was created and managed manually.

```typescript
await manager.release();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sparklytical.gitbook.io/typeorm/entity-manager-and-repository/untitled.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
