Search code examples
typescripttypeorm

typeorm: what is the difference between getRepository() and getConnection()?


https://typeorm.io/#/select-query-builder/how-to-create-and-use-a-querybuilder

There are several ways how you can create a Query Builder:

Using connection:

import {getConnection} from "typeorm";

const user = await getConnection()
    .createQueryBuilder()
    .select("user")
    .from(User, "user")
    .where("user.id = :id", { id: 1 })
    .getOne();

Using entity manager:

import {getManager} from "typeorm";

const user = await getManager()
    .createQueryBuilder(User, "user")
    .where("user.id = :id", { id: 1 })
    .getOne();

Using repository:

import {getRepository} from "typeorm";

const user = await getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getOne();

The documentation never explains the difference among these methods. When to use each method?


Solution

  • Take a look at the source code:

    getConnection():

    /**
     * Gets connection from the connection manager.
     * If connection name wasn't specified, then "default" connection will be retrieved.
     *
     * @deprecated
     */
    export function getConnection(connectionName: string = "default"): DataSource {
        return getConnectionManager().get(connectionName)
    }
    

    getRepository()

    /**
     * Gets repository for the given entity class.
     *
     * @deprecated
     */
    export function getRepository<Entity extends ObjectLiteral>(
        entityClass: EntityTarget<Entity>,
        connectionName: string = "default",
    ): Repository<Entity> {
        return getConnectionManager()
            .get(connectionName)
            .getRepository<Entity>(entityClass)
    }
    

    getManager()

    /**
     * Gets entity manager from the connection.
     * If connection name wasn't specified, then "default" connection will be retrieved.
     *
     * @deprecated
     */
    export function getManager(connectionName: string = "default"): EntityManager {
        return getConnectionManager().get(connectionName).manager
    }
    

    getConnection() returns a DataSource, getRepository() returns a Repository and getManager() returns an EntityManager. All of them have the createQueryBuilder() method, see Repository.ts#L77, DataSource.ts#L555 and EntityManager.ts#L194

    So the differences between them are: