我有三个这样的课程:
Class A {
Long id;
Date d;
String e;
}
Class B {
Long id;
}
Class AB {
Long aId;
Long bId;
}
我必须构建一个CriteriaQuery来实现以下目标:
select distinct(b.id) from b b
inner join ab ab on ab.bid = b.id
inner join a a on a.id = ab.aid
where e = 'SOMETHING'
and a.d in (
select max(aa.d)
from a aa
inner join ab aabb on aa.id = aabb.aid
inner join b bb on bb.id = aabb.bid
where bb.id = b.id
)
但我错过了一些东西,因为:
List<Predicate> predicates = new ArrayList<Predicate>();
Join<B, A> joinAB = root.join("a", JoinType.INNER); // root is Root<B>
Subquery<A> sqA = query.subquery(A.class); // query is CriteriaQuery
Root<A> rootSqA = sqA.from(A.class);
sqA.select(builder.max((Expression)rootSqA.get("d")));
sqA.where(builder.and(joinAB.get("id").in(rootSqA.get("id))));
predicates.add(builder.in(sqA).value((Expression)joinAB.get("d")));
predicates.add(builder.equal(joinAB.get("e"), "SOMETHING"));
我没有得到我想要的东西。我想我得到的是所有C对象(带有他们的最后一个A对象),它们有一个对象A,其中e =&#34; SOMETHING&#34;在某一点。但我想要的是所有C对象的最后一个A对象,其中e =&#34; SOMETHING&#34;。
答案 0 :(得分:1)
经常发生这种情况,在这里发布问题之后,我意识到我只是愚蠢而且我只需要完全理解这个问题,而且最重要的是我使用的框架(我是CriteriaBuilder的新手)和我想出了自己问题的答案。
所以这是:
Join<B, A> joinAB = root.join(B_.a, JoinType.INNER);
Subquery<Date> sqB = query.subquery(Date.class);
Root<B> rootSq = sqB.from(B.class);
Join<B, A> joinSq = rootSq.join(B_.lastA, JoinType.INNER);
sqB.select(builder.max((Expression)joinSq.get(A_.date)));
sqB.where(builder.equal((Expression)rootSq.get(A.id), root.get(A_.id)));
predicates.add(builder.and(
builder.equal(joinAB.get(A_.d), sqB),
builder.equal(joinAB.get(A_.e), "SOMETHING")));