Mybatis+PageHelper分页工具类

一、添加pom依赖

因为使用了sql的解析工具所以需要引入 jsqlparser jar包。

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
<!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser -->
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>3.2</version>
        </dependency>

二、创建分页结果对象

package com.dongliang.lcnorder.util.pagehelper;

import lombok.Data;

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

/**
 * @author D-L
 * @version 1.0.0
 * @ClassName PageUtils.java
 * @Description 分页结果对象
 * @createTime 2021-06-15 15:55:00
 */

@Data
public class PageResult<T extends List> implements Serializable{
    
    private static final long serialVersionUID = -7173074737108151950L;

    //总记录数
    private long total=0;
    
    //结果集
    private List list;

    //当前页码
    private int pageNum=1;
    
    //每页显示条数
    private int pageSize=10;

    //总页数
    private int totalPage=1;
}

三、分页结果处理工具类

package com.dongliang.lcnorder.util.pagehelper;

import com.github.pagehelper.Page;

import java.util.List;

/**
 * @author D-L
 * @version 1.0.0
 * @ClassName PageUtils.java
 * @Description 分页结果处理工具类
 * @createTime 2021-06-15 16:15:00
 */
public class PageUtils {
    public static <T extends List> PageResult<T> build(T list){
        PageResult<T> result = new PageResult<T>();
        if(list == null){
            return new PageResult<T>();
        }
        if (list instanceof Page) {
            Page<T> page = (Page<T>) list;
            result.setPageNum(page.getPageNum());
            result.setPageSize(page.getPageSize());
            result.setTotal(page.getTotal());
            result.setTotalPage(page.getPages());
            result.setList(list);
        }
        return result;
    }
}

四、请求响应模板

package com.dongliang.lcnorder.util.response;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author D-L
 * @version 1.0.0
 * @ClassName ResponseParams.java
 * @Description 请求响应模板
 * @createTime 2021-06-15 16:41:00
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseParams<T> implements Serializable {

    private static final long serialVersionUID = -7173074737108454L;
    //状态(0或1)
    private String status = "0";

    // 错误码
    private String code = "0x00000000";

    //描述信息(成功或失败原因)
    private String message = "";

    //接口名
    private String remark = "";

    private T data;

    public  ResponseParams success(){
        this.status = "1";
        this.message = "【调用成功】";
        this.code = "0x00000000";
        return this;
    }

    public  ResponseParams success(String code , T data){
        this.status = "1";
        this.message ="【调用成功】";
        this.code = code;
        this.data = data;
        return this;
    }

    public  ResponseParams error(){
        this.status = "0";
        this.message = "【调用失败】";
        this.code = "500";
        return this;
    }

    public  ResponseParams error(String code){
        this.status = "0";
        this.message = "【调用失败】";
        this.code = code;
        return this;
    }

    public ResponseParams(String remark) {
        this.remark = remark;
    }
    public ResponseParams(T data) {
this.data = data;
}
}

五、自定义异常

package com.dongliang.lcnorder.util.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
 * @author D-L
 * @version 1.0.0
 * @ClassName ResponseControllerAdvice.java
 * @Description 自定义通用异常
 * @createTime 2021-06-16 09:37:00
 */
@Data
@EqualsAndHashCode(callSuper=false)
@NoArgsConstructor
public class CustomizeException extends RuntimeException {

    private static final long serialVersionUID = -1514051287932579564L;
    
    private  String code;

    private  String msg;

    private  String description;

    public CustomizeException(String msg) {
        super(msg);
        this.msg = msg;
    }
    
    public CustomizeException(String code, String msg, String description) {
        super(msg);
        this.code = code;
        this.msg = msg;
        this.description = description;
    }
}

六、处理全局异常

package com.dongliang.lcnorder.util.response;


import com.dongliang.lcnorder.util.exception.CustomizeException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author D-L
 * @version 1.0.0
 * @ClassName ResponseControllerAdvice.java
 * @Description 处理全局异常
 * @createTime 2021-06-16 09:37:00
 */

@RestControllerAdvice(basePackages = {"com.dongliang.lcnorder.controller"})
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果接口返回的类型本身就是 ResponseParams 那就没有必要进行额外的操作,返回false
        return !methodParameter.getGenericParameterType().equals(ResponseParams.class);
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // String类型不能直接包装,所以要进行些特别的处理
        if (methodParameter.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在 ResponseParams 里后,再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(new ResponseParams<>(data));
            } catch (JsonProcessingException e) {
                // CustomizeException 为自定义异常
                throw new CustomizeException("返回String类型错误");
            }
        }
        // 将原本的数据包装在 ResponseParams 里
        return new ResponseParams<>(data);
    }
}

七、接口入参DTO

package com.dongliang.lcnorder.entity.dto;

import lombok.Data;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * @author D-L
 * @version 1.0.0
 * @ClassName UserListDto.java
 * @Description 用户列表入参dto
 * @createTime 2021-06-15 22:31:00
 */
@Data
public class UserListDto implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotNull(message = "页码不能为空")
    private Integer pageNum;

    @NotNull(message = "每页条数不能为空")
    private Integer pageSize;
}

八、使用

    /**
     * 获取用户列表
     * @param userListDto 入参
     * @return
     */
    @PostMapping("/getUser")
    public ResponseParams getUser(@Validated @RequestBody UserListDto userListDto){
        ResponseParams responseParams = new ResponseParams("查询用户列表");
        PageHelper.startPage(userListDto.getPageNum(),userListDto.getPageSize());
        List<Users> users = orderService.getUser();
        PageResult<List<Users>> pageResult = PageUtils.build(users);
        return responseParams.success("200" , pageResult);
    }

九、结果

 

 十、异常结果

 

posted @ 2021-06-15 18:03  AmourLee  阅读(681)  评论(0编辑  收藏  举报