我可以使用HQL来加载属性吗?

时间:2010-09-10 11:54:18

标签: nhibernate select hql eager-loading

我正在尝试研究如何在以下HQL查询中急切加载客户:

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

订单与客户之间存在通常的多对一关系。

我想这样做是在查询中,而不是映射,如果可能的话 - 就像在“连接提取......”中一样。

也许查询会被重构为连接,而且我有心理障碍。

有什么想法吗?

1 个答案:

答案 0 :(得分:6)

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)

要使其正常工作,您需要在BadItem与Order无关的情况下添加BadItem与Order之间的关系,或者使用具有额外条件的inner join(在使用备选方案2时注意性能)。

替代:

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)
)

编辑:

怎么样:

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)
)