levtatarov
levtatarov

Reputation: 1712

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

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?

Upvotes: 31

Views: 39733

Answers (2)

Abazad
Abazad

Reputation: 51

lamba way with org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor to generate the underscore classes

    static Specification<User> hasRoles(List<String> roles) {
        return (root, query, cb) -> { 
            query.distinct(true);
             Join<User, Account> joinUserAccount = root.join(User_.account);
             Join<Account, AccountRole> acctRolesJoin = joinUserAccount.join(Account_.accountRoles);
             Join<AccountRole, Role> rolesJoin = acctRolesJoin.join(AccountRole_.role);

             return rolesJoin.get(Role_.name).in(roles);
        };
    }

Upvotes: 5

rchukh
rchukh

Reputation: 2947

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);
        }
    };
}

Upvotes: 53

Related Questions