Search code examples
typeorm

In TypeOrm, what are the default fetch types for OneToMany and ManyToOne?


Typeorm's official document states that if you use Lazy, you must use promise. If not promise, will default fetch type be eager loading? However, I checked and it seems to be loading Lazy, not Eager. The default pitch type of JPA is as follows:

OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER

Is TypeOrm's default fetch type the same?


Solution

  • TLDR: It is neither lazy nor eager.


    If you check Typeorm relation options code:

    export interface RelationOptions {
        ...
    
        /**
         * Set this relation to be lazy. Note: lazy relations are promises. When you call them they return promise
         * which resolve relation result then. If your property's type is Promise then this relation is set to lazy automatically.
         */
        lazy?: boolean;
        /**
         * Set this relation to be eager.
         * Eager relations are always loaded automatically when relation's owner entity is loaded using find* methods.
         * Only using QueryBuilder prevents loading eager relations.
         * Eager flag cannot be set from both sides of relation - you can eager load only one side of the relationship.
         */
        eager?: boolean;
    
        ...
    }
    
    

    You can see that Typeorm does not load the relation for any kind of relationship by default. Basically, it is neither lazy nor eager.

    If you set neither lazy nor eager, it will not load the relationship at all unless you specified it in your find options, or in QueryBuilder.

    See the below example from Typeorm Documentation for find:

    const user = userRepository.find({
        where: {
            name: "John",
        },
        relations: ["project"],
    });
    
    // Think user has a one-to-many relationship with projects, then:
    // const projects = user.projects;
    

    If you specify lazy or eager then you don't need to specify it in find options. But you will still have to specify the join condition when using QueryBuilder.

    For lazy:

    const user = userRepository.find({
        where: {
            name: "John",
        }
    });
    
    // Need await for `lazy`:
    // const projects = await user.projects;
    

    For eager:

    const user = userRepository.find({
        where: {
            name: "John",
        }
    });
    
    // No await for `eager`:
    // const projects = user.projects;
    

    Hope this helps. Cheers 🍻 !!!