Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I eager load a property using HQL?

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?

like image 840
dommer Avatar asked Jan 22 '23 11:01

dommer


1 Answers

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)
)
like image 152
Alexander Torstling Avatar answered Jan 30 '23 08:01

Alexander Torstling