2017-02-06 53 views
0

我有三個類這樣的:CriteriaQuery中的子查詢,最大

Class A { 
    Long id; 
    Date d; 
    String e; 
} 

Class B { 
    Long id; 
} 

Class AB { 
    Long aId; 
    Long bId; 
} 

我havetØ建立一個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")); 

,我沒有得到我想要的東西。我想我得到是有對象的隨e =「東西」在某些時候所有的C對象(與他們的最後一個對象)。但我想要的是有他們的最後一個對象,具有E =「東西」的所有C對象。

回答

0

經常發生,在發佈問題後,我意識到我只是愚蠢的,我只需要完全理解問題,最重要的是我使用的框架(我是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")));