• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between "left join" and "left join fetch"  RSS feed

 
Sandeep Vaid
Ranch Hand
Posts: 392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference betweeb the follosing 2 queries:
from Product product left join product.productNamesList where product.productId = '1'
from Product product left join fetch product.productNamesList where product.productId = '1'

I know one advantage of "left join" is that i can alias the joined association and use this alias in with clause as:
from Product product left join product.productNamesList pnList with pnList.name like "%a%" where product.productId = '1'

BUT this is not possible with "left join fetch".

Can we say that "left join fetch" COMPULSORY means FETCH ALL productNames for this product?
 
Sandeep Vaid
Ranch Hand
Posts: 392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Left join" --->

Query q = session.createQuery("from Item i join i.bids b");
Iterator pairs = q.list().iterator();
while ( pairs.hasNext() ) {
Object[] pair = (Object[]) pairs.next();
Item item = (Item) pair[0];
Bid bid = (Bid) pair[1];
}

Instead of a List of Items, this query returns a List of Object[] arrays. At index 0 is the Item, and at index 1 is the Bid. A particular Item may appear multiple times, once for each associated Bid.
These duplicate items are duplicate in-memory references, not duplicate instances!


2. "left join fetch" ---> This is also known as eager dynamic fetching.
from Item i
left join fetch i.bids
where i.description like '%Foo%'

When executed, it returns a list of Item instances, with their bids collections fully initialized. This is quite different if you compare it to the ordered pairs returned by the queries in the previous section!

The corresponding generated SQL will be:
select i.DESCRIPTION, i.INITIAL_PRICE, ...
b.BID_ID, b.AMOUNT, b.ITEM_ID, b.CREATED_ON
from ITEM i
left outer join BID b on i.ITEM_ID = b.ITEM_ID
where i.DESCRIPTION like '%Foo%'

An additional WITH clause wouldn’t make sense here. You can’t restrict the Bid instances: All the collections must be fully initialized.


Personally I don’t agree with author and hibernate team that WITH clause doesn’t make any sense here… Why I am bound to get all the collections? What if I want only those bids whose Amount >100 ?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!