views:

80

answers:

1

I'm trying to work out how to eager load the customers in the following HQL query:

select order.Customer
from Order as order
where order.Id in
(
  select itemId
  from BadItem as badItem
  where (badItemType = :itemType) and (badItem.Date >= :yesterday)
)

There's the usual many-to-one relationship between orders and customers.

I'd like to do this is in the query, as opposed to the mapping, if possible - as in a "join fetch..."

Maybe the query would be refactored as a join and I'm having a mental block.

Any ideas?

+3  A: 
select customer
from BadItem as badItem
join fetch badItem.Order as order
left join fetch order.Customer as customer 
where (badItemType = :itemType) and (badItem.Date >= :yesterday)

For this to work you will need to add the relationship between BadItem and Order if BadItem is unrelated to Order, or use an inner join with extra conditions (watch out for performance when using alternative 2).

Alternative:

select customer
from Order as order
join fetch order.Customer as customer
where order.Id in
(
  select itemId
  from BadItem as badItem
  where (badItemType = :itemType) and (badItem.Date >= :yesterday)
)

EDIT:

What about:

select customer
from Order as order
join fetch order.Customer customer
join fetch customer.orders 
where order.Id in
(
  select itemId
  from BadItem as badItem
  where (badItemType = :itemType) and (badItem.Date >= :yesterday)
)
disown
Thanks for the help. I'm trying your "alternative" query first, but am getting a " Query specified join fetching, but the owner of the fetched association was not present in the select list" error. Any ideas? I'll try you first suggestion once I can work out how to map BadItem and Order (the key in the BadItems table is effectively three columns - not my design).
dommer
Hmm, It sound like the reason is that if you select the customers, they will be populated already. So that basically means that your questions is moot; if you select the customers directly, the customers cannot be lazy loaded (hibernate doesn't support lazy loading on attribute level) and are therefore already loaded. Could this be it?
disown
One would have thought so, but my original query throws a LazyInitializationException for Customer._orders (_orders is the backing field for the Order property).
dommer
What about my last edit?
disown
Yes. It's looking good now. Problem solved. Think I had another issue that was confusing things, but all sorted now.
dommer