懒加载与急加载
TypeORM 提供了两种加载数据关系的主要方式:懒加载(Lazy Loading)和急加载(Eager Loading)。两者对你应用的性能有不同影响。
懒加载
懒加载只在需要时才加载关系数据,当并非总是需要全部关联数据时,它能降低数据库负载。
@Entity()
export class User {
@OneToMany(() => Post, (post) => post.user, { lazy: true })
posts: Promise<Post[]>
}当你需要取回数据时,只需调用
const user = await userRepository.findOneBy({ id: userId })
const posts = await user.posts优点:
- 资源高效:只在真正需要时才加载必要的数据,降低查询成本与内存占用。
- 适合选择性使用数据的场景:适用于并非所有关联数据都需要的场合。
缺点:
- 查询复杂度上升:每次访问关联数据都会额外触发一次数据库查询,如果管理不当可能增加延迟。
- 难以追踪:使用不慎可能导致 n+1 查询问题。
急加载
急加载会在主查询执行时自动取回所有关联数据。这很方便,但如果存在过多复杂关系,可能引发性能问题。
@Entity()
export class User {
@OneToMany(() => Post, (post) => post.user, { eager: true })
posts: Post[]
}在这种情况下,一旦取回 user 数据,posts 也会被加载。
优点:
- 自动加载关联数据,让你无需额外查询就能更轻松地访问关系。
- 避免 n+1 查询问题:由于所有数据都在单条查询中取回,不存在产生不必要的多条查询的风险。
缺点:
- 一次性取回所有关联数据可能产生很大的查询,即使并非所有数据都被需要。
- 不适合只需要关联数据中一部分的场景,因为它可能导致数据使用低效。
要深入了解如何配置和使用懒加载与急加载关系的更多细节和示例,请访问 TypeORM 官方文档:急加载与懒加载关系
TypeORM provides two main methods for loading data relations: Lazy Loading and Eager Loading. Each has a different impact on the performance of your application.
Lazy loading
Lazy loading loads the relation data only when needed, reducing database load when all related data isn't always necessary.
@Entity()
export class User {
@OneToMany(() => Post, (post) => post.user, { lazy: true })
posts: Promise<Post[]>
}When you need to retrieve the data, simply call
const user = await userRepository.findOneBy({ id: userId })
const posts = await user.postsAdvantages:
- Resource efficiency: Only loads the necessary data when actually required, reducing query costs and memory usage.
- Ideal for selective data usage: Suitable for scenarios where not all related data is needed.
Disadvantages:
- Increased query complexity: Each access to related data triggers an additional query to the database, which may increase latency if not managed properly.
- Difficult to track: Can lead to the n+1 query problem if used carelessly.
Eager Loading
Eager loading automatically retrieves all related data when the main query is executed. This can be convenient but may cause performance issues if there are too many complex relations.
@Entity()
export class User {
@OneToMany(() => Post, (post) => post.user, { eager: true })
posts: Post[]
}In this case, posts will be loaded as soon as user data is retrieved.
Advantages:
- Automatically loads related data, making it easier to access relationships without additional queries.
- Avoids the n+1 query problem: Since all data is fetched in a single query, there's no risk of generating unnecessary multiple queries.
Disadvantages:
- Fetching all related data at once may result in large queries, even if not all data is needed.
- Not suitable for scenarios where only a subset of related data is required, as it can lead to inefficient data usage.
To explore more details and examples of how to configure and use lazy and eager relations, visit the official TypeORM documentation: Eager and Lazy Relations