如何解决 N+1 Selects 问题? [英] How can i resolve the N+1 Selects problem?

查看:23
本文介绍了如何解决 N+1 Selects 问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解如何在 jpa 或 hibernate 中避免 n+1 选择.

I have trouble understanding how to avoid the n+1 select in jpa or hibernate.

从我读到的内容来看,有左连接获取",但我不确定它是否仍然适用于多个列表(oneToMany)..

From what i read, there's the 'left join fetch', but i'm not sure if it still works with more than one list (oneToMany)..

谁能给我解释一下,或者给我一个清晰完整解释的链接?

Could someone explain it to me, or give me a link with a clear complete explanation please ?

如果这是一个菜鸟问题,我很抱歉,但我找不到关于这个问题的真正清晰的文章或文档.

I'm sorry if this is a noob question, but i can't find a real clear article or doc on this issue.

谢谢

推荐答案

除了 join 之外,您还可以使用 subselect(s).这会导致执行 2 个查询(或者通常 m + 1,如果您有 m 个列表),但它也适用于大量列表,这与 join 不同取.

Apart from the join, you can also use subselect(s). This results in 2 queries being executed (or in general m + 1, if you have m lists), but it scales well for a large number of lists too, unlike join fetching.

使用连接提取,如果您使用实体提取 2 个表(或列表),您将获得 笛卡尔积,即来自两个表的行对的所有组合.如果表很大,结果可能会巨大,例如如果两个表都有 1000 行,则笛卡尔积包含 100 万行!

With join fetching, if you fetch 2 tables (or lists) with your entity, you get a cartesian product, i.e. all combinations of pairs of rows from the two tables. If the tables are large, the result can be huge, e.g. if both tables have 1000 rows, the cartesian product contains 1 million rows!

对于这种情况,更好的选择是使用子选择.在这种情况下,您将发出 2 个选择 - 每个表一个 - 在主选择(加载父实体)之上,因此您总共加载 1 + 100 + 100 行和 3 个查询.

A better alternative for such cases is to use subselects. In this case, you would issue 2 selects - one for each table - on top of the main select (which loads the parent entity), so altogether you load 1 + 100 + 100 rows with 3 queries.

对于记录,延迟加载同样会导致 201 个单独的选择,每个选择加载一行.

For the record, the same with lazy loading would result in 201 separate selects, each loading a single row.

更新:以下是一些示例:

  • a tutorial: Tuning Lazy Fetching, with a section on subselects towards the end (btw it also explains the n+1 selects problem and all strategies to deal with it),
  • examples of HQL subqueries from the Hibernate reference,
  • just in case, the chapter on fetching strategies from the Hibernate reference - similar content as the first one, but much more thorough

这篇关于如何解决 N+1 Selects 问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆