开发者

JPA Criteria join

I have two entity classes with many to one relation. I need to select all the p开发者_JAVA技巧arent records that has a child record with a min value smaller than provided.

@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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜