Hibernate Criteria, Select order according to newest events
I have classes in hibernate like this:
@Entity
class Order{
private MyPattern pat;
@Id
private int id;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "order_id")
private List<Event> events;
public DetachedCriteria getCriteria() {
//here I create criterias
}
}
@Entity
class Event{
@Column
@Temporal(value = javax.persistence.TemporalType.DATE)
private Date date;
@Id
private int id;
@Column
private String name;
}
What I need is to create DetachedCriteria in Order from MyPattern(detail structure is not important). I have this partially implemented, but my problem now is to s开发者_运维百科elect only Orders that have newest event.name like one in pattern. I think maybe selecting row with nevest date would help, But I just cant figure out, how to do this in Criteria. So I am open to solutions and help. Thanks
edit: I have request, which is Order. I have to respond with correct Order instance(according to content of pattern). For example: Client requesting only orders which was already shipped. So I need to select Orders which has newest Event with name "Shipped".
DetachedCriteria dc=DetachedCriteria.forClass(Order.class,"or").CreateAlias("events","eve");
dc.add(Restriction.eq("eve.name","Shipped"));
orders=dc.getExecutableCriteria(session).list();
Basicky this code should do the trick but it has one BIG flaw. It returns even orders which were "Delivered" because events in Order is List which contains every event on order. So maybe simple fix like "select orders which has event.name=Shipped but NOT event.name=Delivered.
Fetching results based on event name pattern & ordered by date. Event_ & Order_ are metamodel classes of Event & Order entity.
CriteriaQuery<Order> cq = cb.createQuery(Order.class);
Root<Order> order = cq.from(Order.class);
Join<Order, Event> event = cq.join(Order_.events);
cq.select(order);
cq.where(cb.like(event.get(Event_.name)), "*somePattern"); // pattern for results
cq.orderBy(cb.asc(event.get(Event_.date));
精彩评论