If you want to achieve,
1. Pagination,
2. Search in all String columns,
3. Sort By,
4. Sorting order
in same service/request then this is for you!
I am really impressed with Michail Michailidis' answer and I did update it in my way so that it can be used for any Entity with Pagination (with page number and page size dynamic), sort by, sort order etc.
First of all copy this class at your end:
public class EntitySpecification {
public static <T> Specification<T> textInAllColumns(String text) {
if (!text.contains("%")) {
text = "%" + text + "%";
}
final String finalText = text;
return (Specification<T>) (root, cq, builder) ->
builder.or(root.getModel()
.getDeclaredSingularAttributes()
.stream()
.filter(a -> a.getJavaType()
.getSimpleName().equalsIgnoreCase("string"))
.map(a -> builder.like(root.get(a.getName()), finalText)
).toArray(Predicate[]::new)
);
}
}
Now, in your service class, for example in your UserService class
if you want to achieve something like users list along with search, sort, pagination etc, then use this only
Pageable paging;
if (paginationRequest.getSortOrder().matches("ASC")) {
paging = PageRequest.of(paginationRequest.getPageNo(),
paginationRequest.getPageSize(), Sort.by(
paginationRequest.getSortBy()).ascending());
} else {
paging = PageRequest.of(paginationRequest.getPageNo(),
paginationRequest.getPageSize(), Sort.by(paginationRequest.getSortBy()).descending());
}
List<User> userList = userRepository.findAll(
EntitySpecification.textInAllColumns(paginationRequest.getSearch())
, paging).getContent();
Now don't get confused here,
PaginationRequest
is request POJO class with getters
and setters
having following initially,
Integer pageNo = 0;
Integer pageSize = 10;
String sortBy = "createdTimeStamp";
String sortOrder;
String search = "";