简化分页功能

本文展示了如何使用MyBatis进行分页查询,并通过Service层、ResultPage工具类和PageUtil工具类实现分页结果的封装。ScoreExchangParams参数类用于接收查询条件,包括页码和每页条数。MyBatis XML中定义了查询方法,结合HashMap处理分页参数。返回的数据结构包含当前页、每页大小、总页数、总条数及数据列表。
摘要由CSDN通过智能技术生成

直接上代码实战

1.service层代码

public ResultPage<ScoreExchange> getListPageByParams(ScoreExchangParams params) {

    logger.info("[ScoreExchangeServiceImpl]..getListPageByParams params=", JSON.toJSONString(params));

     ResultPage<ScoreExchange> resultPage = null;

     HashMap<String, Object> param = params.toParamsMap();

     //格式化分页数据

     param = PageUtil.getPageMap(param);

     //查询总数

     Integer totalCount = scoreExchangeMapper.getPageCountByParam(param);

     //查询列表

     List<ScoreExchange> list = scoreExchangeMapper.getPageListByParam(param);

     resultPage = new ResultPage<ScoreExchange>(totalCount, (Integer) param.get("pageSize"), (Integer) param.get("pageNo"), list);

     logger.info("[ScoreExchangeServiceImpl]..getListPageByParams resultPage=", JSON.toJSONString(resultPage));

     return resultPage;

}

2.ResultPage工具类代码

package cn.wanda.giffen.model;

import java.io.Serializable;

import java.util.List;

public class ResultPage<T> implements Serializable {

    private final static int DEFAULT_NAVIGATOR_SIZE = 10;

    // 当前页

    private int currentPage = 1;

    // 每页显示数量

    private int pageSize = 20;

    //总页数

    private int pageCount = 1;

    // 总条数

    private int totalCount;

    private boolean havaNextPage;

    private boolean havePrePage;

    private int navigatorSize;

    // 存放查询结果用的list

    private List<T> items;

    public ResultPage() {

    }

    public ResultPage(int totalCount, int pageSize, int currentPage) {

        this(totalCount, pageSize, currentPage, DEFAULT_NAVIGATOR_SIZE);

    }

    public ResultPage(int totalCount, int pageSize, int currentPage,

                      int navigatorSize) {

        this.totalCount = totalCount;

        this.pageSize = pageSize;

        this.currentPage = currentPage;

        this.pageCount  = operatorPageCount();

        this.navigatorSize = navigatorSize;

    }

    public ResultPage(int totalCount, int pageSize, int currentPage,

                      List<T> items) {

        this.totalCount = totalCount;

        this.pageSize = pageSize;

        this.currentPage = currentPage;

        this.pageCount  = operatorPageCount();

        this.items = items;

    }

    /**

     * 计算总页数

     * @return

     */

    public int operatorPageCount() {

        int pageCount = 0;

        if (pageSize != 0) {

            pageCount = totalCount / pageSize;

            if (totalCount % pageSize != 0)

                pageCount++;

        }

        return pageCount;

    }

    public int getCurrentPage() {

        currentPage = currentPage < pageCount ? currentPage

                : pageCount;

        currentPage = currentPage < 1 1 : currentPage;

        return currentPage;

    }

    public int getPageCount() {

        return pageCount;

    }

    public int getPageSize() {

        return pageSize;

    }

    public int getTotalCount() {

        return totalCount;

    }

    public boolean isHaveNextPage() {

        havaNextPage = false;

        if ((pageCount > 1) && (pageCount> getCurrentPage()))

            havaNextPage = true;

        return havaNextPage;

    }

    public boolean isHavePrePage() {

        havePrePage = false;

        if ((pageCount > 1) && (currentPage > 1))

            havePrePage = true;

        return havePrePage;

    }

    private int getNavigatorIndex(boolean isBegin) {

        int beginNavigatorIndex = getCurrentPage() - navigatorSize / 2;

        int endNavigatorIndex = getCurrentPage() + navigatorSize / 2;

        beginNavigatorIndex = beginNavigatorIndex < 1 1 : beginNavigatorIndex;

        endNavigatorIndex = endNavigatorIndex < pageCount ? endNavigatorIndex

                : pageCount;

        while ((endNavigatorIndex - beginNavigatorIndex) < navigatorSize

                && (beginNavigatorIndex != 1 || endNavigatorIndex != pageCount)) {

            if (beginNavigatorIndex > 1)

                beginNavigatorIndex--;

            else if (endNavigatorIndex < pageCount)

                endNavigatorIndex++;

        }

        if (isBegin)

            return beginNavigatorIndex;

        else

            return endNavigatorIndex;

    }

    public int getBeginNavigatorIndex() {

        return getNavigatorIndex(true);

    }

    public int getEndNavigatorIndex() {

        return getNavigatorIndex(false);

    }

    public List<T> getItems() {

        return items;

    }

    public void setItems(List<T> items) {

        this.items = items;

    }

    public void setCurrentPage(int currentPage) {

        this.currentPage = currentPage;

    }

    public void setPageSize(int pageSize) {

        this.pageSize = pageSize;

    }

    public void setTotalCount(int totalCount) {

        this.totalCount = totalCount;

    }

    public void setPageCount(int pageCount) {

        this.pageCount = pageCount;

    }

}

3.PageUtil工具类

package cn.wanda.giffen.util;

import java.util.HashMap;

public class PageUtil {

    public static HashMap<String,Object> getPageMap(HashMap<String,Object> map){

        if(map!=null){

            Integer _start = Integer.parseInt(map.get("pageNum").toString());

            Integer _size =  Integer.parseInt(map.get("numPerPage").toString());

            int startIndex = 0;

            if(_start!=null && _size!=null){

                if(_start>=1){

                    startIndex = (_start - 1)*_size;

                }else{

                    _start = 0;

                    _size = 20;

                    startIndex = 0;

                }

            }else{

                _start = 0;

                _size = 20;

                startIndex = 0;

            }

            map.put("pageNo", _start);

            map.put("pageSize", _size);

            map.put("startIndex", startIndex);

        }

        return map;

    }

}

4.ScoreExchangParams 入参格式

package cn.wanda.giffen.model.params;

import cn.wanda.giffen.model.ScoreExchange;

import com.google.common.collect.Maps;

import lombok.Data;

import java.lang.reflect.Field;

import java.util.HashMap;

@Data

public class ScoreExchangParams extends ScoreExchange {

    /**

     * 页码

     */

    private int pageNum;

    /**

     * 每页显示条数

     */

    private int numPerPage;

    public HashMap<String, Object> toParamsMap(){

        HashMap<String, Object> paramsMap = Maps.newHashMap();

        Field[] fieldList = this.getClass().getSuperclass().getDeclaredFields();

        for (Field field : fieldList){

            try {

                field.setAccessible(true);

                paramsMap.put(field.getName(), field.get(this));

            catch (IllegalAccessException e) {

                e.printStackTrace();

            }

        }

        fieldList = this.getClass().getDeclaredFields();

        for (Field field : fieldList){

            try {

                field.setAccessible(true);

                paramsMap.put(field.getName(), field.get(this));

            catch (IllegalAccessException e) {

                e.printStackTrace();

            }

        }

        return paramsMap;

    }

    public int getPageNum() {

        return pageNum;

    }

    public void setPageNum(int pageNum) {

        this.pageNum = pageNum;

    }

    public int getNumPerPage() {

        return numPerPage;

    }

    public void setNumPerPage(int numPerPage) {

        this.numPerPage = numPerPage;

    }

}

5.mybaties xml代码格式

<select id="getPageListByParam" parameterType="java.util.HashMap" resultMap="BaseResultMap">

    SELECT

    <include refid="Base_Column_List" />

    FROM score_exchange

    <include refid="getPageWhereCondition"/>

    <if test="startIndex != null and pageSize !=null ">

        limit #{startIndex}, #{pageSize}

    </if>

</select>

<select id="getPageCountByParam" parameterType="java.util.HashMap" resultType="java.lang.Integer">

    SELECT count(id)

    FROM score_exchange

    <include refid="getPageWhereCondition"/>

</select>

6.数据展示

{

  "code""0000",

  "message""成功",

  "status""OK",

  "data": {

    "currentPage"1,

    "pageSize"20,

    "pageCount"1,

    "totalCount"10,

    "havePrePage"false,

    "items": [

      {

        "id"1,

        "businessCode""www",

        "businessName""222",

        "proportionFrom"1,

        "proportionTo"2,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"2,

        "businessCode""bbw",

        "businessName""333",

        "proportionFrom"2,

        "proportionTo"4,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"3,

        "businessCode""eeee",

        "businessName""888",

        "proportionFrom"null,

        "proportionTo"null,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"5,

        "businessCode""xx",

        "businessName""999",

        "proportionFrom"null,

        "proportionTo"null,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"7,

        "businessCode""x",

        "businessName""999",

        "proportionFrom"null,

        "proportionTo"null,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"8,

        "businessCode""b",

        "businessName""999",

        "proportionFrom"null,

        "proportionTo"null,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"9,

        "businessCode""s",

        "businessName""999",

        "proportionFrom"null,

        "proportionTo"null,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"10,

        "businessCode""sss",

        "businessName""888",

        "proportionFrom"null,

        "proportionTo"null,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"12,

        "businessCode""eeeiie",

        "businessName""888",

        "proportionFrom"null,

        "proportionTo"null,

        "valid"1,

        "createTime"null,

        "createBy"null,

        "modifyTime"null,

        "modifyBy"null

      },

      {

        "id"13,

        "businessCode""www444",

        "businessName""5555",

        "proportionFrom"0,

        "proportionTo"0,

        "valid"1,

        "createTime"null,

        "createBy""string",

        "modifyTime"null,

        "modifyBy"0

      }

    ],

    "haveNextPage"false,

    "beginNavigatorIndex"1,

    "endNavigatorIndex"1

  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值