这是我编写的更复杂的 HQL 查询之一。在这种能力下,我对 HQL 还是很陌生,可以使用一些反馈。
我会在本机 sql 中做的一件事是将日期comarison 内容更改为来自单个查询作为表,即
FROM
(
SELECT MIN, MAX
FROM ..
) T
这是方法:
public IList<Order> GetOrdersBy(string referenceNumber = null, int? customerId = null, int? carrierId = null, DateTime? startDate = null,
DateTime? endDate = null, int? websiteId = null, OrderStatus? status = null)
{
var byStatusHql =
@"
select odor
from Order odor
join fetch odor._orderStatusLog statusLog
where
(:referenceNumber is null or odor.Quote.ReferenceNumber=:referenceNumber) and
(:customerId is null or odor.Quote.Customer.CustomerID=:customerId) and
(:carrierId is null or odor.Quote.Carrier.CarrierID=:carrierId) and
(:websiteId is null or odor.Quote.Customer.Website.WebsiteID=:websiteId) and
(
:startDate is null or :startDate >
(select min(CreatedDate) from OrderStatusLog lg where lg in elements(odor._orderStatusLog))
) and
(
:endDate is null or :endDate <=
(select max(CreatedDate) from OrderStatusLog lg where lg in elements(odor._orderStatusLog))
) and
(
:status is null or :status =
(
select Status from OrderStatusLog lg where lg in elements(odor._orderStatusLog)
and lg.OrderStatusLogID = (select max(OrderStatusLogID) from OrderStatusLog lgg where lgg in elements(odor._orderStatusLog))
)
)
";
var query = Session.CreateQuery(byStatusHql);
query.SetParameter("referenceNumber", referenceNumber)
.SetParameter("customerId", customerId)
.SetParameter("carrierId", carrierId)
.SetParameter("websiteId", websiteId)
.SetParameter("startDate", startDate)
.SetParameter("endDate", endDate)
.SetParameter("status", status)
;
return query.List<Order>();
}