JPA criteria API - Matching against a list in Spring Data JPA Specifications

levtatarov picture levtatarov · Dec 18, 2012 · Viewed 24.1k times · Source

i'm want to create a specification that matches a group id of a user object against a list of ids. i was thinking about using isMember (like in the code) but the method won't take the list.

public static Specification<User> matchCompanyIdsList(final List<Long> groupIds){
  return new Specification<User>() {
    public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder){
      final Path<Group> group = root.<Group> get("group");
      return builder.isMember(company.<Long>get("id"), companyIds);
    }
  };
}

if i'm off, the how would i do it otherwise?

Answer

rchukh picture rchukh · Dec 19, 2012

Do you want to create a specification that matches all users that have group id, which are in the groupsIds list?

If so, you could use something like this (Which will use SQL IN clause):

public static Specification<User> matchCompanyIdsList(final List<Long> groupIds){
    return new Specification<User>() {
        public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder){
            final Path<Group> group = root.<Group> get("group");
            return group.in(groupIds);
        }
    };
}