Java + mybatis 分頁查詢後臺實現(三層實現全部過程)

1:java分頁查詢後臺實現的基本過程

注意:實現原理:瞭解一個sql語句

select * from coupon_card  LIMIT #{offset}, #{limit}
解釋:offset :查詢結果的索引值(默認從0開始),當offset=0時可省略offset
	 limit  :爲查詢結果返回的數量

本次測試coupon_card表有22條數據
例如: 索引爲0 返回的數量爲10 獲取的就是coupon_card表的前1~10條數據
索引爲10 返回的數量爲10 獲取的就是coupon_card表的11~20條數據
索引爲20 返回的數量爲10 獲取的就是coupon_card表的21~30條數據

controller

@GetMapping("/coupon/ceshifenye")
    public Result<?> getCeShiFenYe(@RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        CouponPageBO result=couponService.getCeShiFenyePage(pageNo,pageSize);
        IPage ipage=new Page<>();
        ipage.setTotal(result.getTotal());//總共有多少條數據
        ipage.setSize(pageSize);//每頁大小(也就是每頁最多多少條數據)
        ipage.setRecords(result.getList());//分頁的當前頁數據
        ipage.setCurrent(pageNo);//分頁的當前頁頁碼
        return Result.ok(ipage);
    }

service(接口層)

CouponPageBO getCeShiFenyePage(Integer pageNo, Integer pageSize);

ServiceImpl(實現類)

@Override
    public CouponPageBO getCeShiFenyePage(Integer pageNo, Integer pageSize) {
        CouponPageBO couponPageBO = new CouponPageBO();
        //查詢分頁數據
        int offert=(pageNo - 1) * pageSize;
        couponPageBO.setList(couponCardMapper.getFenYeShuJu(offert,pageSize));
        //查詢分頁總數據數
        couponPageBO.setTotal(couponCardMapper.getFenYeZongTiaoShu());
        return couponPageBO;
    }

Mapper

/**
     * 測試分頁---查詢分頁數據
     * @param offert
     * @param pageSize
     * @return
     */
    List<CouponBO> getFenYeShuJu(@Param("offset") int offert,
                                 @Param("limit") Integer pageSize);

    /**
     * 測試分頁---查詢分頁總數
     * @return
     */
    Integer getFenYeZongTiaoShu();

xml

<!--測試分頁查詢-查詢分頁數據-->
    <select id="getFenYeShuJu" resultType="org.mall.modules.pojo.promotion.bo.CouponBO">
        select
       *
        from coupon_card
        LIMIT #{offset}, #{limit}
    </select>
    <!-- 測試分頁查詢-查詢分頁總數-->
    <select id="getFenYeZongTiaoShu" resultType="Integer">
        select
        COUNT(1)
        FROM coupon_card
    </select>

使用的工具類

IPage

/*
 * Copyright (c) 2011-2020, baomidou ([email protected]).
 * <p>
 * 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
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 com.baomidou.mybatisplus.core.metadata;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import static java.util.stream.Collectors.toList;

/**
 * 分頁 Page 對象接口
 *
 * @author hubin
 * @since 2018-06-09
 */
public interface IPage<T> extends Serializable {

    /**
     * 降序字段數組
     *
     * @return order by desc 的字段數組
     * @see #orders()
     */
    @Deprecated
    default String[] descs() {
        return null;
    }

    /**
     * 升序字段數組
     *
     * @return order by asc 的字段數組
     * @see #orders()
     */
    @Deprecated
    default String[] ascs() {
        return null;
    }

    /**
     * 獲取排序信息,排序的字段和正反序
     *
     * @return 排序信息
     */
    List<OrderItem> orders();

    /**
     * KEY/VALUE 條件
     *
     * @return ignore
     */
    default Map<Object, Object> condition() {
        return null;
    }

    /**
     * 自動優化 COUNT SQL【 默認:true 】
     *
     * @return true 是 / false 否
     */
    default boolean optimizeCountSql() {
        return true;
    }

    /**
     * 進行 count 查詢 【 默認: true 】
     *
     * @return true 是 / false 否
     */
    default boolean isSearchCount() {
        return true;
    }

    /**
     * 計算當前分頁偏移量
     */
    default long offset() {
        return getCurrent() > 0 ? (getCurrent() - 1) * getSize() : 0;
    }

    /**
     * 當前分頁總頁數
     */
    default long getPages() {
        if (getSize() == 0) {
            return 0L;
        }
        long pages = getTotal() / getSize();
        if (getTotal() % getSize() != 0) {
            pages++;
        }
        return pages;
    }

    /**
     * 內部什麼也不幹
     * <p>只是爲了 json 反序列化時不報錯</p>
     */
    default IPage<T> setPages(long pages) {
        // to do nothing
        return this;
    }

    /**
     * 分頁記錄列表
     *
     * @return 分頁對象記錄列表
     */
    List<T> getRecords();

    /**
     * 設置分頁記錄列表
     */
    IPage<T> setRecords(List<T> records);

    /**
     * 當前滿足條件總行數
     *
     * @return 總條數
     */
    long getTotal();

    /**
     * 設置當前滿足條件總行數
     */
    IPage<T> setTotal(long total);

    /**
     * 當前分頁總頁數
     *
     * @return 總頁數
     */
    long getSize();

    /**
     * 設置當前分頁總頁數
     */
    IPage<T> setSize(long size);

    /**
     * 當前頁,默認 1
     *
     * @return 當前頁
     */
    long getCurrent();

    /**
     * 設置當前頁
     */
    IPage<T> setCurrent(long current);

    /**
     * IPage 的泛型轉換
     *
     * @param mapper 轉換函數
     * @param <R>    轉換後的泛型
     * @return 轉換泛型後的 IPage
     */
    @SuppressWarnings("unchecked")
    default <R> IPage<R> convert(Function<? super T, ? extends R> mapper) {
        List<R> collect = this.getRecords().stream().map(mapper).collect(toList());
        return ((IPage<R>) this).setRecords(collect);
    }
}

使用的返回結果封裝類

package org.mall.common.api.vo;

import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.mall.common.constant.CommonConstant;
import lombok.Data;


@Data
@ApiModel(value="接口返回對象", description="接口返回對象")
public class Result<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 成功標誌
	 */
	@ApiModelProperty(value = "成功標誌")
	private boolean success = true;

	/**
	 * 返回處理消息
	 */
	@ApiModelProperty(value = "返回處理消息")
	private String message = "操作成功!";

	/**
	 * 返回代碼
	 */
	@ApiModelProperty(value = "返回代碼")
	private Integer code = 0;
	
	/**
	 * 返回數據對象 data
	 */
	@ApiModelProperty(value = "返回數據對象")
	private T result;
	
	/**
	 * 時間戳
	 */
	@ApiModelProperty(value = "時間戳")
	private long timestamp = System.currentTimeMillis();

	public Result() {
		
	}
	
	public Result<T> error500(String message) {
		this.message = message;
		this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500;
		this.success = false;
		return this;
	}
	
	public Result<T> success(String message) {
		this.message = message;
		this.code = CommonConstant.SC_OK_200;
		this.success = true;
		return this;
	}
	
	
	public static Result<Object> ok() {
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setMessage("成功");
		return r;
	}
	
	public static Result<Object> ok(String msg) {
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setMessage(msg);
		return r;
	}
	
	public static Result<Object> ok(Object data) {
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setResult(data);
		return r;
	}
	
	public static Result<Object> error(String msg) {
		return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg);
	}
	
	public static Result<Object> error(int code, String msg) {
		Result<Object> r = new Result<Object>();
		r.setCode(code);
		r.setMessage(msg);
		r.setSuccess(false);
		return r;
	}
	
	/**
	 * 無權限訪問返回結果
	 */
	public static Result<Object> noauth(String msg) {
		return error(CommonConstant.SC_JEECG_NO_AUTHZ, msg);
	}
}

後臺返回結果

在這裏插入圖片描述

前端測試數據展示

在這裏插入圖片描述

用到的兩個實體類

CouponPageBO

package org.mall.modules.pojo.promotion.bo;

import lombok.Data;
import lombok.experimental.Accessors;

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


@Data
@Accessors(chain = true)
public class CouponPageBO implements Serializable {

    /**
     * 數據 數組
     */
    private List<CouponBO> list;
    /**
     * 總量
     */
    private Integer total;

}

CouponBO

package org.mall.modules.pojo.promotion.bo;

import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * @Description: coupon_card
 * @Date:   2019-12-10
 * @Version: V1.0
 */
@Data
@TableName("coupon_card")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="coupon_card對象", description="coupon_card")
public class CouponBO {
    
	/**創建時間*/
	private java.util.Date createTime;

	/**優惠劵編號*/
	private Integer id;
	/**是否刪除(0:未刪除,1:已刪除)*/
	private Integer isDelete;
	/**折扣*/

	private Integer percentOff;
	/**優惠類型
     *
     * 1-代金卷
     * 2-折扣卷*/

	private Integer preferentialType;
	/**是否設置滿多少金額可用,單位:分
     *
     * 0-不限制
     * 大於0-多少金額可用*/

	private Integer priceAvailable;
	/**優惠金額,單位:分。*/

	private Integer priceOff;
	/**商店id*/

	private String shopId;
	/**優惠碼狀態
     *
     * 1-未使用
     * 2-已使用
     * 3-已失效*/

	private Integer status;
	/**領取類型
     *
     * 1 - 用戶主動領取
     * 2 - 後臺自動發放*/

	private Integer takeType;
	/**優惠劵(碼)分組編號,{@link } 的 id*/

	private Integer templateId;
	/**標題*/

	private String title;
	/**最後更新時間*/

	private java.util.Date updateTime;
	/**使用時間*/
	private java.util.Date usedTime;
	/**用戶編號*/
	private String userId;
	/**生效結束時間*/

	private java.util.Date validEndTime;
	/**生效開始時間*/
	private java.util.Date validStartTime;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章