欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot 利用Pageable插件实现分页和查询

程序员文章站 2022-03-09 23:13:39
...

Spring Boot 利用Pageable插件实现分页和查询

  • Pageable 是spring
    Data库中定义的一个接口,该接口是所有分页相关信息的一个抽象,通过该接口,我们可以得到和分页相关所有信息(例如pageNumber、pageSize等)。
  • Pageable定义了很多方法,但其核心的信息只有两个:一是分页的信息(page、size),二是排序的信息

第一步

在Dao包中书写个数据库的接口

 @Query(value="select * from student inner join classes on classes.cid=student.sid",nativeQuery=true)
    Page<List<Map>> findPage(Pageable pageable);

为什么书写这个page<List<?>>这个返回值呢?

  • 将数据交给page类来分页处理
  • 在显示页面有首页,上一页,下一页,尾页吧,这个就是原因了

第二步

在ServIce包中实现Dao接口

 public Page<List<Map>> findPage(Pageable pageable){
        return studentDao.findPage(pageable);
    }

这样就把pageable这个分页插件给实现了

第三步

这一步就是在Controller这个包中编写

//    分页
    @RequestMapping("/findPage")

    public String findByPage(Model model, Integer pageNum){
//        当前页面为空时,赋值为一,代表是当前为第一页
        if(pageNum==null){
            pageNum=1;
        }
        Pageable pageable=PageRequest.of(pageNum-1,5);
        Page<List<Map>> page=serviceStudent.findPage(pageable);
        model.addAttribute("pageInfo",page);
        return "index";
    }

PageRequest.of(int PageNum,int PageSize):用来设置页面的位置和展示的数据条目数,我们设置每页展示5条数据。PageInfo用来封装页面信息,返回给前台界面。

第四步

这个就是设置一下他的显示效果,单纯的显示层

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<center>
    <h1>山东柏瑞软件科技有限公司</h1>
<table border="1" width="80%"height="80%">
    <tr >
        <td colspan="6">
            <form action="/student/findName">
                <input type="text" name="name">
                <input type="submit"value="查询">
            </form>
        </td>
    </tr>
    <tr>
        <td>编号</td>
        <td>姓名</td>
        <td>成绩</td>
        <td>生日</td>
        <td>班级</td>
        <td>操作</td>
    </tr>
    <tr th:each="student:${pageInfo.content}">
        <td th:text="${student.id}"></td>
        <td th:text="${student.name}"></td>
        <td th:text="${student.score}"></td>
        <td th:text="${student.birthday}"></td>
        <td th:text="${student.cname}"></td>
        <td>
            <a href="/student/toAdd">添加</a>
            <a th:href="@{/student/doDelete(id=${student.id})}">删除</a>
            <a th:href="@{/student/toUpdate(id=${student.id})}">修改</a>
        </td>
    </tr>
</table>
<ul>
    当前第 <span th:text="${pageInfo.number}+1"></span>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;<span th:text="${pageInfo.totalPages}"></span>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;<span th:text="${pageInfo.totalElements}"></span>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;
    <a th:href="@{/student/findPage(pageNum=1)}">首页</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;
    <a th:href="@{/student/findPage(pageNum= ${pageInfo.hasPrevious()}?${pageInfo.getNumber()}:1)}">上一页</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;
    <a th:href="@{/student/findPage(pageNum= ${pageInfo.hasNext()}?${pageInfo.getNumber()}+2:${pageInfo.totalPages})}">下一页</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;
    <a th:href="@{/student/findPage(pageNum= ${pageInfo.totalPages} )}">尾页</a>
</ul>
</center>
</body>
</html>

这个还是可以的,细心点没问题
这些个方法 比如是hasPrevious()(上一页)、pageInfo.hasNext()(下一页)等方法是在哪里来的?
这写个方法是来自Page类的
page 类是继承Slice接口中的
展示一下Slice类

/*
 * Copyright 2014-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.domain;

import java.util.List;
import java.util.function.Function;

import org.springframework.core.convert.converter.Converter;
import org.springframework.data.util.Streamable;

/**
 * A slice of data that indicates whether there's a next or previous slice available. Allows to obtain a
 * {@link Pageable} to request a previous or next {@link Slice}.
 *
 * @author Oliver Gierke
 * @since 1.8
 */
public interface Slice<T> extends Streamable<T> {

	/**
	 * Returns the number of the current {@link Slice}. Is always non-negative.
	 *
	 * @return the number of the current {@link Slice}.
	 */
	int getNumber();

	/**
	 * Returns the size of the {@link Slice}.
	 *
	 * @return the size of the {@link Slice}.
	 */
	int getSize();

	/**
	 * Returns the number of elements currently on this {@link Slice}.
	 *
	 * @return the number of elements currently on this {@link Slice}.
	 */
	int getNumberOfElements();

	/**
	 * Returns the page content as {@link List}.
	 *
	 * @return
	 */
	List<T> getContent();

	/**
	 * Returns whether the {@link Slice} has content at all.
	 *
	 * @return
	 */
	boolean hasContent();

	/**
	 * Returns the sorting parameters for the {@link Slice}.
	 *
	 * @return
	 */
	Sort getSort();

	/**
	 * Returns whether the current {@link Slice} is the first one.
	 *
	 * @return
	 */
	boolean isFirst();

	/**
	 * Returns whether the current {@link Slice} is the last one.
	 *
	 * @return
	 */
	boolean isLast();

	/**
	 * Returns if there is a next {@link Slice}.
	 *
	 * @return if there is a next {@link Slice}.
	 */
	boolean hasNext();

	/**
	 * Returns if there is a previous {@link Slice}.
	 *
	 * @return if there is a previous {@link Slice}.
	 */
	boolean hasPrevious();

	/**
	 * Returns the {@link Pageable} that's been used to request the current {@link Slice}.
	 *
	 * @return
	 * @since 2.0
	 */
	default Pageable getPageable() {
		return PageRequest.of(getNumber(), getSize(), getSort());
	}

	/**
	 * Returns the {@link Pageable} to request the next {@link Slice}. Can be {@link Pageable#unpaged()} in case the
	 * current {@link Slice} is already the last one. Clients should check {@link #hasNext()} before calling this method.
	 *
	 * @return
	 * @see #nextOrLastPageable()
	 */
	Pageable nextPageable();

	/**
	 * Returns the {@link Pageable} to request the previous {@link Slice}. Can be {@link Pageable#unpaged()} in case the
	 * current {@link Slice} is already the first one. Clients should check {@link #hasPrevious()} before calling this
	 * method.
	 *
	 * @return
	 * @see #previousPageable()
	 */
	Pageable previousPageable();

	/**
	 * Returns a new {@link Slice} with the content of the current one mapped by the given {@link Converter}.
	 *
	 * @param converter must not be {@literal null}.
	 * @return a new {@link Slice} with the content of the current one mapped by the given {@link Converter}.
	 * @since 1.10
	 */
	<U> Slice<U> map(Function<? super T, ? extends U> converter);

	/**
	 * Returns the {@link Pageable} describing the next slice or the one describing the current slice in case it's the
	 * last one.
	 *
	 * @return
	 * @since 2.2
	 */
	default Pageable nextOrLastPageable() {
		return hasNext() ? nextPageable() : getPageable();
	}

	/**
	 * Returns the {@link Pageable} describing the previous slice or the one describing the current slice in case it's the
	 * first one.
	 *
	 * @return
	 * @since 2.2
	 */
	default Pageable previousOrFirstPageable() {
		return hasPrevious() ? previousPageable() : getPageable();
	}
}

那么number,totalElements 这些个方法在哪里呢?
Spring Boot 利用Pageable插件实现分页和查询
这里的totalPages(总页) total Elements:(数据的总条数) size :(一个界面中有多少条数据)