Typeorm is very helpful tool when working with PostgreSQL. It has many built in features to help the developers. Among all of those features eager is one of them.
eager relations are loaded automatically each time you load entities from the database. For example, when Test is loaded the items table will be automatically joined and populated.
@Entity()
export class Test{
@PrimaryGeneratedColumn('uuid')
id: string;
@OneToMany(() => TestItem, (item) => item.test, { eager: true })
items: Array<TestItem>;
}
It seems fun only if it is totally independent from other entities. But when the Test entity itself is joined to other entities then problem occurs.
Here are few downfall of using eager:
Memory overload when the Test has too many items
As earlier said if its joint in other tables/entities where items is not needed, then in that case we can not disable eager loading of items which is redundant.
It always makes sures to load items or (eager loaded other relation) even for simple queries.
Performance issue as the eager always loads all linked relations.
Might cause maximum call stack memory exceeded error.
Developers might forget the eager has been used and use extra relations on typeorm query or join table on query builder.
Might go to infinite circular dependencies as below:
@Entity()
class TestItem {
@ManyToOne(() => Test, (test) => test.items, { eager: true })
test: Test;
}
Here Test tries to eager load TestItem and vice versa which will cause circular dependencies.
Solution
Only load the relations whenever needed as:
- Use relations with typeorm
await Test.find({
relations: ['items']
});
- Use join with query builder
await Test.createQueryBuilder('test')
.leftJoinAndSelect('test.items', 'items')
.getMany();
Have you ever used eager and forgot that you have used and just go with relations causing eventually the tragedy of performance loading???
Top comments (0)