Created
January 15, 2021 23:08
-
-
Save yuripourre/489bffb09c5782347768ad521bdb53ff to your computer and use it in GitHub Desktop.
Spring JPA GenericSpecification for GROUP BY and WHERE IN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company.jpa; | |
import org.springframework.data.jpa.domain.Specification; | |
import javax.persistence.criteria.Expression; | |
import java.util.Collection; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class GenericSpecifications<T> { | |
public Specification<T> groupBy(Specification<T> specification, List<String> columnNames) { | |
return (Specification<T>) (root, query, criteriaBuilder) -> { | |
List<Expression<?>> columnNamesExpression = columnNames.stream().map(x -> root.get(x)).collect(Collectors.toList()); | |
query.groupBy(columnNamesExpression); | |
return specification.toPredicate(root, query, criteriaBuilder); | |
}; | |
} | |
public Specification<T> whereIn(String columnName, Collection<String> value) { | |
return (Specification<T>) (root, query, criteriaBuilder) -> root.get(columnName).in(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment