《Java Persistence with Hibernate(第2版)》关联查询有效性问询
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
Iteminstances that have at least oneBidwith an amount > 20. Theleft joinis effectively turned into an inner join by thewhereclause, because anyItemwithout matchingBids will haveb.amountasnull, which failsnull > 20.The book’s point is about intent: The author is addressing a common misconception: if your goal is to load all
Iteminstances, but only populate theirbidscollection withBids where amount > 20, this query does NOT do that. Instead, it filters out anyItemthat doesn’t have qualifyingBids entirely. Even for theItems that are returned, Hibernate won’t reliably restrict thebidscollection to only the qualifyingBids (depending on your fetch strategy, it might still load all associatedBids later, or populate the collection with all matches from the result set—but the core issue is you can’t use awhereclause 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
Iteminstances, even those with noBids at all. - For
Items that haveBids with amount > 20, theirbidscollection is initialized with only those qualifyingBids. - For
Items with no qualifyingBids, theirbidscollection 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

