You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《Java Persistence with Hibernate(第2版)》关联查询有效性问询

Understanding Hibernate Fetch Joins with Filtered Collections

Great question—let’s unpack this step by step, since fetch joins and filtering can be confusing at first.

Why the first query is "invalid" (per the book)

The book flags select i from item i left join fetch i.bids b where b.amount > 20 as invalid, but your observation that it behaves like an inner join is correct—here’s why the distinction matters:

  • Your interpretation is technically accurate: This query will only return Item instances that have at least one Bid with an amount > 20. The left join is effectively turned into an inner join by the where clause, because any Item without matching Bids will have b.amount as null, which fails null > 20.

  • The book’s point is about intent: The author is addressing a common misconception: if your goal is to load all Item instances, but only populate their bids collection with Bids where amount > 20, this query does NOT do that. Instead, it filters out any Item that doesn’t have qualifying Bids entirely. Even for the Items that are returned, Hibernate won’t reliably restrict the bids collection to only the qualifying Bids (depending on your fetch strategy, it might still load all associated Bids later, or populate the collection with all matches from the result set—but the core issue is you can’t use a where clause on the joined entity to filter the collection while retaining all parent entities).

Is the second query valid?

Yes! The query select i from item i left join fetch i.bids b on b.amount > 20 is fully valid in modern Hibernate versions (and aligns with JPA 2.1+ standards).

This uses an on clause to apply the filter directly to the join, rather than filtering the entire result set. Here’s what it does:

  • Returns all Item instances, even those with no Bids at all.
  • For Items that have Bids with amount > 20, their bids collection is initialized with only those qualifying Bids.
  • For Items with no qualifying Bids, their bids collection will be empty (not null).

This is exactly the behavior the book mentions you can’t get with the first query—loading all parents while filtering their child collections.


内容的提问来源于stack exchange,提问作者flamant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:12:39