@Entity
class Parent; {
String source;
}
@Entity
class child { @ManyToOne Parent parent; int value; }What I need is to select all the Parent classes where Parent.source = X and min(Child.value> < Y. How to add the join on the parent/child entity and the specific select criteria?
CriteriaBuilder cb = context.em().getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Parent.class);
Root r = cq.from(Parent.class);
Predicate p = cb.conjunction();
p = cb.and(p, cb.equal(r.get("source"), X));
Expression y = cb.literal(Y);
// what to do with y?
cq.where(p);
TypedQuery tq = context.em().createQuery(cq);
tq.setFirstResult(0);
tq.setMaxResults(100);
return tq.getResultList();
Might be easier if the parent has a child OneToMany back. But with your current model it should be something like,
CriteriaBuilder cb = context.em().getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Parent.class);
Root r = cq.from(Parent.class);
Root child = cq.from(Child.class);
Predicate p = cb.and(cb.equal(r.get("source"), X), cb.equal(child.get("parent"), r));
Predicate p = cb.and(p, cb.lt(child.get("value"), Y)));
cq.where(p);
TypedQuery tq = context.em().createQuery(cq);
tq.setFirstResult(0);
tq.setMaxResults(100);
return tq.getResultList();
That would be any child has a value less than the value. For all of, you would need to do a sub query.
精彩评论