JPA extends SimpleJpaRepository.findAll to support all queries with a page number of -1

Business scene

The company's front-end framework references datatable.js. The paging format is shown in the figure below. It supports 10, 20, 50, 100, and all. The previous digital pages can be directly passed into JPA through the Spring assembly object to complete the paging, but all queries fail.
write picture description here

solution

1. Find the paging parameters in the datatable.js source code and find the following code

"lengthMenu": [[10, 20, 50, 100, -1],[10, 20, 50, 100, "全部"]],

It can be seen from this that when we select "all" on the page, the parameter of the number of pages passed into the background is -1

2. Find the "find all" function in JPA, and find the following function that matches our judgment of the number of pages

    public Page<T> findAll(Specification<T> spec, Pageable pageable) {
        TypedQuery<T> query = getQuery(spec, pageable);
        return pageable == null ?
                       new PageImpl<T>(query.getResultList()) : readPage(query, pageable, spec);
    }

It can be seen from this that JPA judges whether the pageable is empty. When it is empty, it returns all the content. When it is not empty, it requests the corresponding paging data according to the number of pages requested. Therefore, as long as we support paging when the number of pages is -1, we can set pageable=null when it is judged to be -1, so that all data can be returned, and the code after the new code is added.

    public Page<T> findAll(Specification<T> spec, Pageable pageable) {
        TypedQuery<T> query = getQuery(spec, pageable);
        /**新增内容开始*/
        //当判断前台传来的页数为-1的时候,手动置pageable为null
        if(pageable.getPageSize()==-1){
            pageable = null;
        }
        /**新增内容结束*/
        return pageable == null ?
                       new PageImpl<T>(query.getResultList()) : readPage(query, pageable, spec);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521508&siteId=291194637