Search code examples
sqljpapredicatebuilder

How to build an "IN" clause in JPA using Predicates?


I wanna build a query to return me data matching by "Role" and list of "Id", but I can't understand very well how the syntax should be.

I tried to follow the working examples with that use only "equal" clause but it does not work. The code follows

public static Specification<CustomerUser> findByIdsAndRole(List<Long> ids, String role) {
    return new Specification<CustomerUser>() {

        private static final long serialVersionUID = -3381908547196927973L;

        public Predicate toPredicate(Root<CustomerUser> root, CriteriaQuery<?> query, CriteriaBuilder builder) {

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

            if (ids != null) {
                predicates.add(builder.in(root.get("id"), ids));
                predicates.add(builder.equal(root.get("role"), role));
            }

            return builder.and(predicates.toArray(new Predicate[0]));
        }
    };
}

It gives me an error, it tells me to remove the argument "ids" from it. But if I run the code like this I get the this error log:

org.postgresql.util.PSQLException: ERRO: syntax error at or near ")"


Solution

  • Please try predicates.add(root.get("id").in(ids)));.