Spring Data - Multi-column searches

前端 未结 5 1966
心在旅途
心在旅途 2020-12-01 10:05

I am using Spring Data for the paging and the sorting. However, I would like to perform multi-columns searches.

Now, I am using the annotation @Query in my r

5条回答
  •  情歌与酒
    2020-12-01 10:36

    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  Specification textInAllColumns(String text) {
            if (!text.contains("%")) {
                text = "%" + text + "%";
            }
            final String finalText = text;
    
            return (Specification) (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 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 = "";
    

提交回复
热议问题