Java 极客营 L2资料

springboot 分页实现

2020-05-28  本文已影响0人  IT职业与自媒体思考

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

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

<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可以得到你想要的数据。

上一篇 下一篇

猜你喜欢

热点阅读