Home > Back-end >  JPA Criteria API - A "NOT IN" predicate to exclude some entities by ID
JPA Criteria API - A "NOT IN" predicate to exclude some entities by ID

Time:10-04

I am struggling understanding how I can go about making a "NOT IN" like query.

Basically I have a root Agent. These agents have a UUID id.

I want to add a predicate to my list of predicates to that any agents with an ID in a given Set/Collection of UUIDs are excluded in the query.

Not sure entirely how to go about it but I see there is an IN but no NOT IN but there is a isNotMember...

@Override
public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {

    root.fetch(Agent_.TAGS, JoinType.LEFT);
    query.distinct(true);

    List<Predicate> predicateList = new ArrayList<>();

    if(!excludedAgents.isEmpty()){
      
        // Excluded Agents is a Set<UUID> of the Agent Ids to exclude.
        Predicate notMember = criteriaBuilder.isNotMember(????);
        predicateList.add(notMember);

    }

    //More predicates here added....

    return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
}

Thank you for any help!

CodePudding user response:

isMember/isNotMember is meant for checking if a certain entity is not part of toMany relationship.

What you are looking for is

builder.not(root.get("id").in(uuids))
  • Related