Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 866
levtatarov Avatar asked Dec 18 '12 19:12

levtatarov


People also ask

What is Spring JPA specification?

Specifications provide us with a way to write reusable queries and also fluent APIs with which we can combine and build more sophisticated queries. All in all, Spring JPA Specifications is a great tool whether we want to create reusable predicates or want to generate typesafe queries programmatically.

What is JPA Criteria API?

Java Prime Pack The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax. Similar to JPQL it follows abstract schema (easy to edit schema) and embedded objects.

Is Spring data JPA an implementation of the JPA specification?

Spring Data JPA is not an implementation or JPA provider, it's just an abstraction used to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.

What is @query annotation in spring boot?

The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm. xml file. It's a good approach to place a query definition just above the method inside the repository rather than inside our domain model as named queries.


1 Answers

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);         }     }; } 
like image 105
rchukh Avatar answered Sep 29 '22 05:09

rchukh