hibernate 如何决定默认使用哪个 FetchMode?

How hibernate decide which of FetchMode use by default?

在我们的项目中,我们使用 Hibernate,并且在日志中我们观察到当我们没有指定 FetchMode 时,它​​有时使用 Join 有时使用 Select 关系(据我所知是 FetchMode)。

如果没有指定,Hibernate 如何决定使用哪一种 FetchMode?

这个有什么规范吗?任何代码行?有文章吗?

在没有指定FetchMode且FetchType为EAGER时查看生成的SQL,Hibernate中默认为JOIN

遗憾的是,我在官方文档中找不到这些信息。

关于 SELECT 的使用,即使 JOIN 是默认的,我认为有些查询无法在一个查询中解决,like this:

But if you allow B without C, Hibernate just HAS TO check presence of C at the moment it loads B. But a SELECT to check presence is just inefficient because the same SELECT may not just check presence, but load entire object. So lazy loading goes away.

如果字段上不存在 Hibernate 注释 @Fetch,则该字段的默认 FetchMode 是:

  • 如果该字段的 FetchType = EAGER,则 FetchMode = JOIN。
  • 否则,FetchMode = SELECT.

我获取此信息的来源是代码本身 (Hibernate 5.0):HERE, HERE and most importantly, HERE.

如果字段未使用 @Fetch 注释,则此字段的默认 FetchMode 取决于 FetchType 以及查询的完成方式:

  • FetchType.LAZY => FetchMode.SELECT
  • FetchType.EAGER:
    • 通过 ID 获取 (Session.get) => FetchMode.JOIN
    • JPQL 查询 => FetchMode.SELECT
    • 条件API查询=>FetchMode.SELECT