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

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

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

第一步

在需要分页的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);
    }

第三步

这一步就是在控制层(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):用来设置页数和每页中显示的数据条数。

  • int PageNum: 页数
  • int PageSize: 每页显示的数据条数

PageInfo:接收后端接口中的数据,渲染给显示界面。

第四步

现在我们在postman当中请求,看看接口给我返回的数据我们分析下
在这里插入图片描述
pageSize: 每页显示的数据条数;
PageNumber: 页数
totalPages: 总页数
totalElements: 总条数

<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>

这个还是可以的,细心点没问题
这些个方法 比如是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();
	}
}

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
使用 Spring Boot 和 Vue 实现分页的基本思路如下: 1. 后端 Spring Boot 通过接收前端传入的分页参数(例如当前页码和每页显示数量),从数据库中查询对应数据,并返回给前端。 2. 前端 Vue 将后端返回的数据渲染到页面上,并通过 UI 组件显示分页导航栏。 3. 当用户点击分页导航栏时,前端 Vue 将对应的分页参数传递给后端 Spring Boot后端重新查询数据并返回给前端进行渲染。 具体实现方式可以参考以下步骤: 1. 后端 Spring Boot 需要接收前端传入的分页参数,这些参数一般包括当前页码、每页显示数量等。可以使用 Spring Framework 提供的 Pageable 类来接收分页参数,例如: ``` @GetMapping("/users") public Page<User> getUsers(Pageable pageable) { return userService.getUsers(pageable); } ``` 其中,`userService.getUsers(pageable)` 方法会根据 Pageable 对象中的分页参数查询对应的用户数据并返回一个 Page 对象。 2. 前端 Vue 需要将后端返回的分页数据渲染到页面上,并显示分页导航栏,可以使用 UI 组件库(例如 ElementUI)提供的 Pagination 组件来实现。例如: ``` <template> <div> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> </tr> </thead> <tbody> <tr v-for="user in users" :key="user.id"> <td>{{ user.name }}</td> <td>{{ user.age }}</td> </tr> </tbody> </table> <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize" :total="total" layout="prev, pager, next" > </el-pagination> </div> </template> <script> export default { data() { return { users: [], currentPage: 1, pageSize: 10, total: 0, }; }, mounted() { this.fetchUsers(); }, methods: { fetchUsers() { axios .get("/users", { params: { page: this.currentPage - 1, size: this.pageSize, }, }) .then((response) => { this.users = response.data.content; this.total = response.data.totalElements; }); }, handlePageChange(page) { this.currentPage = page; this.fetchUsers(); }, }, }; </script> ``` 其中,Pagination 组件的 `current-page`、`page-size` 和 `total` 分别对应当前页码、每页显示数量和数据总数,`@current-change` 事件用于监听分页导航栏的点击事件,并将对应的页码传递给后端进行查询。 3. 当用户点击分页导航栏时,前端 Vue 会将对应的分页参数传递给后端 Spring Boot后端重新查询数据并返回给前端进行渲染。具体实现方式与第一步类似,可以使用 Pageable 对象接收分页参数,并根据分页参数查询对应数据。例如: ``` @GetMapping("/users") public Page<User> getUsers(Pageable pageable) { return userService.getUsers(pageable); } ``` 需要注意的是,前端传递的分页参数中的页码是从 1 开始计数的,而 Spring Framework 中的 Pageable 对象中的页码是从 0 开始计数的,因此需要在前端传递分页参数时将页码减一。例如: ``` axios .get("/users", { params: { page: this.currentPage - 1, size: this.pageSize, }, }) ``` 这样就可以使用 Spring Boot 和 Vue 实现分页了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平平常常一般牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值