Hi there,
I'm new to Criteria and I'm having a bit of trouble trying to generate a query.
I have the following object structure where status change events for a given order are stored in a separate history table:
Order { customerId, displayableOrderId, List<OrderStatusChange>, ... }
OrderStatus { description, ... }
OrderStatusChange { order, orderStatus, statusChangedDate, ... }
I'm trying to list all orders which have had a status change within a specified time interval for a given customer; in SQL I would write:
Code:
select o.CUSTOMER_ID, o.DISPLAYABLE_ORDER_ID, o...
from ORDERS o
inner join ORDER_STATUS_CHANGES s on o.ORDER_ID = s.ORDER_ID
where o.CUSTOMER_ID = :customerId
and s.STATUS_CHANGED_DATE between :statusChangedStartDate and :statusChangedEndDate
group by o.CUSTOMER_ID, o.DISPLAYABLE_ORDER_ID, o...
order by max(s.STATUS_CHANGED_DATE) desc, o.DISPLAYABLE_ORDER_ID;
So far, I have the following hibernate criteria. The problem is that I'm not sure how I can get it to group by all the properties of the order class and have it return an instance of an Order. Right now, this is throwing a ClassCastException when it attempts to cast the results list to the typed Order list because, well they aren't Order instances.
Code:
DetachedCriteria q = DetachedCriteria.forClass(Order.class)
.createAlias("orderStatusChanges", "s")
.setProjection(projectionList()
.add(max("s.statusChangedDate"), "maxStatusChangedDate")
.add(groupProperty("displayableOrderId")))
.add(eq("customerId", customerId))
.add(between("s.statusChangedDate", statusChangedStartDate, statusChangedEndDate))
.addOrder(desc("maxStatusChangedDate"))
.addOrder(asc("displayableOrderId"));
result = (List<Order>)getHibernateTemplate().findByCriteria(q, firstResult, noOfResults);
Here is the SQL that hibernate generated:
Code:
select
*
from
( select
row_.*,
rownum rownum_
from
( /* criteria query */ select
max(s1_.STATUS_CHANGED_DATE) as y0_,
this_.DISPLAYABLE_ORDER_ID as y1_
from
ORDERS this_
inner join
ORDER_STATUS_CHANGES s1_
on this_.ORDER_ID=s1_.ORDER_ID
where
this_.CUSTOMER_ID=?
and s1_.STATUS_CHANGED_DATE between ? and ?
group by
this_.DISPLAYABLE_ORDER_ID
order by
y0_ desc,
this_.DISPLAYABLE_ORDER_ID asc ) row_
where
rownum <= ?
)
where
rownum_ > ?
Any ideas what I'm doing wrong?
Thanks,
J