Jpa 在CriteriaBuilder中添加where条件NotIn子查询

final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<Person> cq = cb.createQuery(Person.class);
final Root<Person> root = cq.from(Person.class);
cq.select(root);

final Subquery<Integer> subquery = cq.subquery(Integer.class);
final Root<Person> validityIDSQ = subquery.from(Person.class);
subquery.select(cb.max(validityIDSQ.get(Person_.validityID)));
subquery.groupBy(validityIDSQ.get(Person_.personID));

cq.where(cb.in(root.get(Person_.validityID)).value(subquery));

// 将生成

select
    person0_.id as id1_0_,
    person0_.personID as personID2_0_,
    person0_.validityID as validity3_0_,
    person0_.value as value4_0_
from
    person person0_
where
    person0_.validityID in (
            select
                max(person1_.validityID)
            from
                person person1_
            group by
                person1_.personID)

 

自身所需NotIn语法,所以是

                Subquery<String> manageUserSubquery = query.subquery(String.class);
                Root<RelationUserManagePlateDomain> relationUserManagePlateDomainRoot = manageUserSubquery.from(RelationUserManagePlateDomain.class);
                Join<RelationUserManagePlateDomain, UserDomain> relationUserManagePlateDomainUserDomainJoin = relationUserManagePlateDomainRoot.join(RelationUserManagePlateDomain_.user, JoinType.INNER);
                Subquery<String> subquery = manageUserSubquery.select(relationUserManagePlateDomainUserDomainJoin.get(UserDomain_.id));
                Predicate predicate1 = criteriaBuilder.and(criteriaBuilder.not(criteriaBuilder.in(root.get(UserDomain_.id)).value(manageUserSubquery)));
                predicate.getExpressions().add(predicate1);

 

 

借鉴:

    1.https://www.baidu.com/link?url=UT6AeXPjKVapQC9ksgJ1EEg9KiLMP3yCwS3J8aZMCu7Bcv3a69s9G5Q6MZfEhsNi3e_Wwmj9SBfI7d6bBC9dy_&wd=&eqid=d15aaba20003b81d000000035dcbe7fb(这里说明了在Where条件中添加In子查询语法)

    2.https://stackoverflow.com/questions/21383435/jpa-criteriabuilder-not-in-a-collection(这里说明了怎么添加NotIn语法)

     

 

posted @ 2019-11-13 20:08  星小梦  阅读(7532)  评论(0编辑  收藏  举报