springboot 中 分页实现

本次要讲的是典型的两种分页方式,即sql分页和插件分页。

一、sql分页

基于sql语句的分页,不需要特殊依赖。

1.1 依赖

因为使用了mybatis、mysql ,所以要添加相关依赖。这里版本没有特别需求,选择你想要的版本即可。

			 <!--mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis-version}</version>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-version}</version>
            </dependency>

本人使用的版本:

 <mybatis-version>1.3.1</mybatis-version>
 <mysql-version>5.1.32</mysql-version>

1.2 Dao层

ArticleMapper .java中,分页函数如下:

package com.sqlb.mapper;

import com.sqlb.pojo.Article;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.Map;

@Mapper
public interface ArticleMapper {


    /**
     *sql 分页
     */
    List<Article> list(Map<String, Object> map); 
}

对应的ArticleMapper .xml中如下:

  <select id="list" resultType="com.sqlb.pojo.Article">
        select
        <include refid="Base_Column_List"/>
        from article
        <where>
            <if test="id != null and id != ''">and id = #{id}</if>
            <if test="author != null and author != ''">and author = #{author}</if>
            <if test="createTime != null and createTime != ''">and create_time = #{createTime}</if>
            <if test="typeName != null and typeName != ''">and type_name = #{typeName}</if>
            <if test="imageUrl != null and imageUrl != ''">and image_url = #{imageUrl}</if>
            <if test="content != null and content != ''">and content = #{content}</if>
        </where>
        <choose>
            <when test="createTime != null and createTime.trim() != ''">
                order by ${createTime}
            </when>
            <otherwise>
                order by id desc
            </otherwise>
        </choose>
        <if test="offset != null and limit != null">
            limit #{offset}, #{limit}
        </if>
    </select>

1.3 Service层

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public List<Article> list(Integer pageNum, Integer pageSize) {
        return articleMapper.list(PageParam.getParams(pageNum, pageSize));
    }
}

1.4 Controller层

@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @ResponseBody
    @RequestMapping("/list")
    public List<Article> list(@RequestParam(defaultValue = "1",value = "currentPage") Integer pageNum,
                              @RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize){
        return articleService.list(pageNum,pageSize);
    } 
}

当然,使用mybatis记得在application.yml中配置一把,以及mysql数据连接池配置。

mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: mybatis/*/*Mapper.xml
  type-aliases-package: com.sqlb.pojo

mysql数据连接池配置这里就不用多说了吧。不知道的,就赶紧去学习下基础知识。

Article类和表结构

  • Article类
import java.util.Date;

public class Article {
    private Integer id;

    private String author;

    private Date createTime;

    private String typeName;

    private String imageUrl;

    private String content;

	  //此处省去get、set方法
}
  • 表结构
CREATE TABLE `article` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id编号',
 `content` text NOT NULL COMMENT '文章内容,代码控制不可超过1000字',
 `author` varchar(128) DEFAULT NULL COMMENT '作者',
 `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
 `type_name` enum('0','1','2','3','4') NOT NULL DEFAULT '1' COMMENT '文章类型',
 `image_url` varchar(255) DEFAULT NULL COMMENT '图片地址',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4;

sql分页就是这么多了,运行访问http://localhost:8081/article/list可以得到你想要的数据。

二、插件分页

显然,这种方法是要导入第三方jar包的,具体方法如下。

2.1 插件依赖

		   <!--分页插件-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>${pagehelper-version}</version>
            </dependency>

这里要说明一下,本人使用的版本是:

<pagehelper-version>1.1.1</pagehelper-version>

本人开始使用的是当前最新版本1.2.4,本人这里不行,内部原因不详。您如果使用抛错的话,建议可以切换不同版本试试。

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.4</version>
</dependency>

2.2 配置

springboot最大的特色就是只需简单的配置,就可以进行快捷的开发,配置如下:

pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

需要特别注意的是pagehelper.reasonable=true时,当页码增加时,如果没有分页数据了,会一直返回最后一页的数据。建议使用pagehelper.reasonable=false

2.3 Dao层

ArticleMapper .java

import com.github.pagehelper.Page;
import com.sqlb.pojo.Article;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.Map;

@Mapper
public interface ArticleMapper {

    /**
     * 插件 分页 查询表中部分字段
     */
    Page<Article> findByPage();
    /**
     * 插件 分页  查询表中所有字段
     */
    Page<Article> findWithBLOBsByPage();

}

ArticleMapper .xml

    <select id="findByPage" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from article
    </select>
    <select id="findWithBLOBsByPage" resultMap="ResultMapWithBLOBs">
        select
        <include refid="Base_Column_List"/>
        ,
        <include refid="Blob_Column_List"/>
        from article
    </select>

这里有两个分页,不同点就是findWithBLOBsByPage把所有的字段都查询出来了,而findByPage相比之下少查询了一个字段。这里需要提出的是,本人的使用findByPage查询部分字段时,会报java.lang.NoSuchMethodException错误,具体原因暂时不详,以后明白了再记出来,如果哪个大神明白细节的还望不吝赐教~~~

2.4 Service层

此处才用到PageHelper插件


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sqlb.mapper.ArticleMapper;
import com.sqlb.pojo.Article;
import com.sqlb.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;  

    @Override
    public Page<Article> findByPage(Integer pageNum, Integer pageSize) {
        //用插件进行分页
        PageHelper.startPage(pageNum, pageSize);
        return articleMapper.findByPage();
    }

    @Override
    public Page<Article> findWithBLOBsByPage(Integer pageNum, Integer pageSize) {
        //用插件进行分页
        PageHelper.startPage(pageNum, pageSize);
        return articleMapper.findWithBLOBsByPage();
    }
}

2.5 Controller层

首先要创建一个返回给前端的pojo对象,新建一个分页数据类PageInfo

import com.github.pagehelper.Page;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @描叙: 分页 数据结构
 */
public class PageInfo<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    //当前页
    private int pageNum;
    //每页的数量
    private int pageSize;
    //总记录数
    private long total;
    //总页数
    private int pages;
    //结果集
    private List<T> list;
    //是否为第一页
    private boolean isFirstPage = false;
    //是否为最后一页
    private boolean isLastPage = false;


    public PageInfo() {
    }

    /**
     * 包装Page对象
     *
     * @param list
     */
    public PageInfo(List<T> list) {
        if (list instanceof Page) {
            Page page = (Page) list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();

            this.pages = page.getPages();
            this.list = page;
            this.total = page.getTotal();
        } else if (list instanceof Collection) {
            this.pageNum = 1;
            this.pageSize = list.size();

            this.pages = 1;
            this.list = list;
            this.total = list.size();
        }
        if (list instanceof Collection) {
            //判断页面边界
            judgePageBoudary();
        }
    }

    /**
     * 判定页面边界
     */
    private void judgePageBoudary() {
        isFirstPage = pageNum == 1;
        isLastPage = pageNum == pages;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public boolean isIsFirstPage() {
        return isFirstPage;
    }

    public void setIsFirstPage(boolean isFirstPage) {
        this.isFirstPage = isFirstPage;
    }

    public boolean isIsLastPage() {
        return isLastPage;
    }

    public void setIsLastPage(boolean isLastPage) {
        this.isLastPage = isLastPage;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("PageInfo{");
        sb.append("pageNum=").append(pageNum);
        sb.append(", pageSize=").append(pageSize);
        sb.append(", total=").append(total);
        sb.append(", pages=").append(pages);
        sb.append(", list=").append(list);
        sb.append(", isFirstPage=").append(isFirstPage);
        sb.append(", isLastPage=").append(isLastPage);
        sb.append(", navigatepageNums=");
        sb.append('}');
        return sb.toString();
    }
}

ArticleController.java中,数据转换如下:

import com.github.pagehelper.Page;
import com.sqlb.pojo.Article;
import com.sqlb.pojo.PageInfo;  //刚才新建的分页数据对象
import com.sqlb.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @ResponseBody
    @RequestMapping("/page")
    public PageInfo<Article> findWithBLOBsByPage(@RequestParam(defaultValue = "1",value = "currentPage") Integer pageNum,
                              @RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize){

        Page<Article> articles = articleService.findWithBLOBsByPage(pageNum, pageSize);
        // 需要把Page包装成PageInfo对象才能序列化。该插件也默认实现了一个PageInfo
        PageInfo<Article> pageInfo = new PageInfo<>(articles);
        return pageInfo;
    }
}

插件分页就是这么多了,运行访问http://localhost:8081/article/list可以得到你想要的数据。

  • 11
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值