版权声明:转载请注明原创 https://blog.csdn.net/qq_42151769/article/details/89923500
这个博客增加一些使用的工具整合业务使用,并且使用pagehelper进行分页
前面一篇博客已经配置了pagehelper,如下:
增加依赖:
<!--pagehelper 分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!--pagehelper 分页插件-->
在application.yml中配置分页:
为了统一结果返回,封装两个返回值类
分页参数返回类:
package com.hf.commonmapper.result;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: 统一封装分页数据
* @Date: 2019/5/7
* @Auther:
*/
public class PageResult<T> implements Serializable {
private static final long serialVersionUID = 8163854998178877689L;
private int totalCount;
private int pageSize;
private int currPage;
private List<T> list;
private boolean hasMore;
public PageResult() {
}
public PageResult(List<T> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
}
public PageResult(List<T> list, int totalCount, int pageSize) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
}
public PageResult(int currPage, int pageSize) {
this.currPage = currPage;
this.pageSize = pageSize;
}
public int getTotalCount() {
return this.totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return this.pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrPage() {
return this.currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<T> getList() {
if (this.list == null || this.list.isEmpty()) {
this.list = new ArrayList(0);
}
return this.list;
}
public void setList(List<T> list) {
this.list = list;
}
public boolean isHasMore() {
return this.totalCount - this.currPage * this.pageSize > 0 ? true:false;
}
public void setHasMore(boolean hasMore) {
this.hasMore = hasMore;
}
}
返回结果类:
package com.hf.commonmapper.result;
import com.hf.commonmapper.enums.BussiEnum;
import java.io.Serializable;
/**
* @Description: 统一返回值
* @Date: 2019/5/7
* @Auther:
*/
public class Response<T> implements Serializable {
private static final long serialVersionUID = 3917809036328685480L;
private String msg;
private Integer code;
private T data;
private Boolean success;
private String exception;
private Integer errCode;
private Response() {
}
private Response(String msg, Integer code, T data, Boolean success) {
this.msg = msg;
this.code = code;
this.data = data;
this.success = success;
this.errCode = code;
}
public Response(String msg, T data, Boolean success) {
this.msg = msg;
this.data = data;
this.success = success;
}
public Response(String msg, Boolean success) {
this.msg = msg;
this.success = success;
}
public Response(String msg, Integer code, T data, Boolean success, String exception) {
this.msg = msg;
this.code = code;
this.data = data;
this.success = success;
this.exception = exception;
}
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getCode() {
return this.code;
}
public void setCode(Integer code) {
this.code = code;
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Integer getErrCode() {
return this.errCode;
}
public void setErrCode(Integer errCode) {
this.errCode = errCode;
}
public static Response createSuccess(String msg) {
return createSuccess(msg, (String[])null);
}
public static Response createSuccess(Object data) {
return createSuccess(BussiEnum.SCUESS.getMsg(), data);
}
public static Response createSuccess(String msg, Object data) {
return createSuccess(msg, BussiEnum.SCUESS.getCode(), data);
}
public static Response createSuccess(String msg, Object data, String... args) {
return createFormatMsg(msg, BussiEnum.SCUESS.getCode(), data, true, args);
}
public static Response createSuccess(String msg, String... args) {
return createFormatMsg(msg, BussiEnum.SCUESS.getCode(), (Object)null, true, args);
}
public static Response createSuccess(String msg, Integer code, Object data) {
return new Response(msg, code, data, true);
}
public Boolean isSuccess() {
return this.success;
}
public Boolean isError(){
return !this.success;
}
public Boolean getSuccess() {
return this.success;
}
public String getException() {
return this.exception;
}
public void setException(String exception) {
this.exception = exception;
}
public static Response createSuccess() {
return new Response(BussiEnum.SCUESS.getMsg(), BussiEnum.SCUESS.getCode(), (Object)null, true);
}
public static Response createError() {
return new Response(BussiEnum.ERROR.getMsg(), BussiEnum.ERROR.getCode(), (Object)null, false);
}
public static Response createError(String msg) {
return createFormatMsg(msg, BussiEnum.ERROR.getCode(), (Object)null, false);
}
public static Response createError(String msg, String... args) {
return createFormatMsg(msg, BussiEnum.ERROR.getCode(), (Object)null, false, args);
}
public static Response createError(String msg, Object data, String... args) {
return createFormatMsg(msg, BussiEnum.ERROR.getCode(), data, false, args);
}
public static Response createError(String msg, Object data) {
return new Response(msg, BussiEnum.ERROR.getCode(), data, false);
}
public static Response createError(String msg, Integer code, Object data) {
return new Response(msg, code, data, false);
}
public static Response createError(String msg, Integer code) {
return createFormatMsg(msg, code, (Object)null, false);
}
public static Response createError(String msg, String exception) {
return new Response(msg, BussiEnum.ERROR.getCode(), (Object)null, false, exception);
}
private static Response createFormatMsg(String msg, Integer code, Object data, Boolean success, String... args) {
return new Response(String.format(msg, args), code, data, success);
}
}
上面两个类用到的枚举定义如下:
package com.hf.autocheck.enums;
import org.springframework.util.CollectionUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Description:
* @Date: 2019/5/5
* @Auther:
*/
public enum ResultEnum {
PROPERTIES_CHECK_SUCCESS(10000,"字段校验成功"),
PROPERTIES_CHECK_ERROR(10001,"字段校验失败")
;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
private Integer code;
private String msg;
public String getMsg(){
return this.msg;
}
public String getMsg(Integer code){
List<ResultEnum> list = Arrays.stream(ResultEnum.values()).filter((ResultEnum var) -> null != code
&& var.code == code).limit(1).collect(Collectors.toList());
return CollectionUtils.isEmpty(list) ? null:list.get(0).getMsg();
}
}
package com.hf.commonmapper.enums;
/**
* @Description:
* @Date: 2019/5/7
* @Auther:
*/
public enum BussiEnum {
SCUESS(200, "成功"),
ERROR(500, "失败");
private Integer code;
private String msg;
private BussiEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return this.code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
引用我以前博客写的一个自动校验对象字段非空的工具类:
PropertiesCheckUtil
package com.hf.commonmapper.utils;
import com.hf.autocheck.enums.ResultEnum;
import com.hf.commonmapper.annotation.NotEmpty;
import com.hf.commonmapper.annotation.NotEmptyIn;
import com.hf.commonmapper.result.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Description: 校验字段非空
* @Date: 2019/4/30
* @Auther:
*/
public class PropertiesCheckUtil {
private static final Logger log = LoggerFactory.getLogger(PropertiesCheckUtil.class);
public static Response<String> autoCheck(Object target){
if(null == target){
return Response.createSuccess(ResultEnum.PROPERTIES_CHECK_ERROR.getMsg());
}
Class<?> clzz = target.getClass();
Field[] fields = FeildReflectUtil.getAllFields(clzz);
//过滤字段
List<Field> list = Arrays.stream(fields).filter((Field var) -> !Modifier.isStatic(var.getModifiers()) && !Modifier.isFinal(var.getModifiers())).collect(Collectors.toList());
for (Field field : list) {
try {
Response<String> response = doCheck(field, target);
if(!response.isSuccess()){
return response;
}
} catch (Exception e) {
log.error("<autoCheck> check properties not empty error....{}" + e.getMessage(),e);
}
}
return Response.createSuccess(ResultEnum.PROPERTIES_CHECK_SUCCESS.getMsg());
}
private static Response<String> doCheck(Field field,Object target) throws Exception {
if(field.isAnnotationPresent(NotEmpty.class)){
Response response = autoMatch(field,target);
if(!response.isSuccess()){
return response;
}
}else if(field.isAnnotationPresent(NotEmptyIn.class)){
if(!field.isAccessible()){
field.setAccessible(true);
}
Response<String> response = deepToCheck(field, field.get(target));
if(!response.isSuccess()){
return response;
}
}else{
return Response.createSuccess(ResultEnum.PROPERTIES_CHECK_SUCCESS.getMsg());
}
return Response.createSuccess(ResultEnum.PROPERTIES_CHECK_SUCCESS.getMsg());
}
private static Response<String> deepToCheck(Field field,Object target) throws Exception {
/* if(null == target){
return Response.createError("<deepToCheck> deep object .... " + field.toGenericString() + " cannot be null...{}");
}*/
//处理list和Map TODO
//handleListAndMap(field,target);
if(field.isAnnotationPresent(NotEmptyIn.class)){
//对有NotEmptyIn注解的字段层层深入,直到没有为止
Class<?> clzz = field.getType().newInstance().getClass();
Field[] fields = FeildReflectUtil.getAllFields(clzz);
//过滤字段
List<Field> list = Arrays.stream(fields).filter((Field var) -> !Modifier.isStatic(var.getModifiers()) && !Modifier.isFinal(var.getModifiers())).collect(Collectors.toList());
for (Field var : list) {
if(var.isAnnotationPresent(NotEmpty.class)){
Response response = autoMatch(var,target);
if(!response.isSuccess()){
return response;
}
}else if(var.isAnnotationPresent(NotEmptyIn.class)){
Class<? extends Class> c = var.getType().getClass();
//获取小对象的值
if(!var.isAccessible()){
var.setAccessible(true);
}
Object o = var.get(target);
Field[] varFields = FeildReflectUtil.getAllFields(clzz);
List<Field> varList = Arrays.stream(fields).filter((Field var2) -> !Modifier.isStatic(var2.getModifiers()) && !Modifier.isFinal(var2.getModifiers())).collect(Collectors.toList());
//递归查找
for (Field var1 : varList) {
Response<String> response = deepToCheck(var1, o);
if(!response.isSuccess()){
return response;
}
}
}
}
}
return Response.createSuccess(ResultEnum.PROPERTIES_CHECK_SUCCESS.getMsg());
}
/**
* 自动匹配对应的类型,用来做相应的处理
* @param
* @return
*/
private static Response autoMatch(Field field,Object target){
if(null == target){
return Response.createError(field.toGenericString() + "can not be null...");
}
//获取字段的类型的名称,在获取到对应的字节码(也就是类型的字节码对象)
Class clzz = field.getType().getName().getClass();
String value = field.getAnnotation(NotEmpty.class).value();
Object o = null;
try {
if(!field.isAccessible()){
field.setAccessible(true);
}
o = field.get(target);
} catch (IllegalAccessException e) {
log.error("<autoMatch> error....{}" + e.getMessage(),e);
}
if(o == null){
return Response.createError(value);
}
if(String.class == clzz){
if(StringUtils.isEmpty(o)){
return Response.createError(value);
}
}
return Response.createSuccess(ResultEnum.PROPERTIES_CHECK_SUCCESS.getMsg());
}
public static Response<String> handleListAndMap(Field field,Object target) throws Exception {
if(null == target){
return Response.createError(field.toGenericString() + "can not be null...");
}
Class clzz = field.getType();
if(List.class == clzz){
//返回一个 Type 对象,它表示此 Field 对象所表示字段的声明类型。
Type type = field.getGenericType();
if(null == type){
return Response.createSuccess(ResultEnum.PROPERTIES_CHECK_SUCCESS.getMsg());
}
//如果是泛型则获取泛型的真实类型
if(type instanceof ParameterizedType){
ParameterizedType parameterizedType = (ParameterizedType) type;
//获取到list数据
List<Object> list = (List<Object>) field.get(target);
//返回表示此类型实际类型参数的 Type 对象的数组。 就是表示泛型的类型,可能有多个,因为预期知道了只有一个,取第一个
Class clss = (Class) parameterizedType.getActualTypeArguments()[0];
}
}else if(Map.class == clzz){
}
return Response.createSuccess(ResultEnum.PROPERTIES_CHECK_SUCCESS.getMsg());
}
public static void main(String[] args) {
}
}
需要配合注解使用,注解定义如下:
package com.hf.commonmapper.annotation;
import java.lang.annotation.*;
/**
* @Description: 非空注解
* @Date: 2019/5/5
* @Auther:
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NotEmpty {
String value();
}
package com.hf.commonmapper.annotation;
import java.lang.annotation.*;
/**
* @Description: 用来渗透进入
* @Date: 2019/5/5
* @Auther:
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NotEmptyIn {
}
还需要依赖一个反射获取字段的工具类,支持获取超类的字段:
FeildReflectUtil
package com.hf.commonmapper.utils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Description: 字段反射工具类
* @Date: 2019/5/5
* @Auther:
*/
public class FeildReflectUtil {
public static Field[] getAllFields(Class<?> clzz){
if(null == clzz){
return null;
}
List<Field> resultList = new ArrayList<>();
while(null != clzz){
resultList.addAll(new ArrayList<>(Arrays.asList(clzz.getDeclaredFields())));
//是否有继承类
clzz = clzz.getSuperclass();
}
Field[] resultArr = new Field[resultList.size()];
return resultList.toArray(resultArr);
}
}
在引用我以前博客写的一个封装的对象复制/集合复制的工具类,BeanUtils
package com.hf.commonmapper.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
/**
* @Description:
* @Date: 2019/5/7
* @Auther:
*/
@Slf4j
public class BeanUtils extends org.springframework.beans.BeanUtils {
public BeanUtils() {
}
public static <T> T propertiesCopy(Object source, Class<T> clazz) {
if (null == source) {
return null;
} else {
try {
T obj = clazz.newInstance();
org.springframework.beans.BeanUtils.copyProperties(source, obj);
return obj;
} catch (IllegalAccessException | InstantiationException var3) {
throw new RuntimeException(var3);
}
}
}
/**
* list中对象的copy
* @param source
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> collectionCopy(Collection source, Class<T> clazz) {
if (null == source) {
return new ArrayList();
} else {
List<T> list = new ArrayList();
Iterator var3 = source.iterator();
while(var3.hasNext()) {
Object o = var3.next();
list.add(propertiesCopy(o, clazz));
}
return list;
}
}
/**
* 将对象转换为map
* @param obj
* @return
*/
public static Map<String, Object> object2Map(Object obj) {
Map<String, Object> map = new HashMap();
if (obj == null) {
return map;
} else {
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
Field[] var4 = fields;
int var5 = fields.length;
for(int var6 = 0; var6 < var5; ++var6) {
Field field = var4[var6];
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
} catch (Exception var8) {
throw new RuntimeException(var8);
}
}
}
/**
* 将map转换为对象,必须保证属性名称相同
* @return
*/
public static Object map2Object(Map<Object,Object> map,Class<?> clzz){
try {
Object target = clzz.newInstance();
if(CollectionUtils.isEmpty(map)){
return target;
}
Field[] fields = clzz.getDeclaredFields();
if(!CollectionUtils.isEmpty(Arrays.asList(fields))){
Arrays.stream(fields).filter((Field field) -> map.containsKey(field.getName())).forEach(var -> {
//获取属性的修饰符
int modifiers = var.getModifiers();
if(Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)){
//在lambada中结束本次循环是用return,它不支持continue和break
return;
}
//设置权限
var.setAccessible(true);
try {
var.set(target,map.get(var.getName()));
} catch (IllegalAccessException e) {
//属性类型不对,非法操作,跳过本次循环,直接进入下一次循环
throw new RuntimeException(e);
}
});
}
return target;
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
/**
* 对象属性复制,忽略为null值的复制,主要是为了防止出现如包装类型:Integer,Double,..等复制后给定默认值0,0.00,....
* @param source
* @param target
* @throws BeansException
*/
public static void copyProperties(Object source, Object target) throws BeansException {
Assert.notNull(source,"source can not be null...{}:" + source);
Assert.notNull(target,"target can not be null...{}:" + target);
Field[] sourceFields = source.getClass().getDeclaredFields();
Field[] targetFields = target.getClass().getDeclaredFields();
if(CollectionUtils.isEmpty(Arrays.asList(sourceFields)) || CollectionUtils.isEmpty(Arrays.asList(targetFields))){
log.error("source all fields size cannot be 0.....");
return;
}
//获取到null值的属性
List<String> nullList = new ArrayList<>();
Arrays.stream(sourceFields).filter((Field var) -> !Modifier.isFinal(var.getModifiers())
&& !Modifier.isStatic(var.getModifiers())).forEach(var1 -> {
Object o = null;
try {
var1.setAccessible(true);
o = var1.get(source);
if(null == o){
nullList.add(var1.getName());
}
} catch (IllegalAccessException e) {
log.error("can not get field value from " + source.toString());
}
});
String[] arr = new String[nullList.size()];
org.springframework.beans.BeanUtils.copyProperties(source,target,nullList.toArray(arr));
}
}
重点注意下这个方法的作用: 因为spring自带的BeanUtil.copy是会当某些字段为null的时候,他是会给定默认值的,
也就是当两个对象的类型不一致时,如source中有一个字段为Boolean类型为null,但是target中对应的类型为boolean,那么在复制的时候是会给默认值为false的
定义入参:
package com.hf.commonmapper.req;
import com.hf.commonmapper.annotation.NotEmpty;
import lombok.Data;
import java.io.Serializable;
/**
* @Description: 基础分页参数
* @Date: 2019/5/7
* @Auther:
*/
@Data
public class BasePageReq implements Serializable {
private static final long serialVersionUID = 7691624103639489037L;
@NotEmpty("分页大小不能为空")
private Integer pageSize;
@NotEmpty("当前页不能为空")
private Integer currPage;
}
上面使用了自定义注解
package com.hf.commonmapper.req;
import java.io.Serializable;
/**
* @Description:
* @Date: 2019/5/7
* @Auther:
*/
public class SpvScheduleLogReq extends BasePageReq implements Serializable {
private static final long serialVersionUID = -7335698140393699997L;
}
定义返回值:
package com.hf.commonmapper.service;
import com.hf.commonmapper.model.SpvScheduleLog;
import com.hf.commonmapper.req.SpvScheduleLogReq;
import com.hf.commonmapper.result.PageResult;
import com.hf.commonmapper.result.Response;
import com.hf.commonmapper.vo.SpvScheDuleLogVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* @Description:
* @Date: 2019/5/7
* @Auther:
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpvScheduleLogServiceTest {
@Autowired
private SpvScheduleLogService spvScheduleLogService;
@Test
public void queryAll(){
List<SpvScheduleLog> logs = spvScheduleLogService.queryAll();
System.out.println("这是啥:" + logs);
}
@Test
public void pageList(){
SpvScheduleLogReq logReq = new SpvScheduleLogReq();
logReq.setCurrPage(1);
logReq.setPageSize(1);
Response<PageResult<SpvScheDuleLogVo>> response = spvScheduleLogService.pageList(logReq);
if(response.isSuccess() && null != response.getData()){
PageResult<SpvScheDuleLogVo> data = response.getData();
System.out.println("当前页:" + data.getCurrPage());
System.out.println("每页大小:" + data.getPageSize());
System.out.println("是否有下一页:" + data.isHasMore());
System.out.println("总页数:" + data.getTotalCount());
System.out.println("数据:" + data.getList().get(0).toString());
}
}
}
下面开始测试:
创建方法分页查询的:
package com.hf.commonmapper.service;
import com.hf.commonmapper.model.SpvScheduleLog;
import com.hf.commonmapper.req.SpvScheduleLogReq;
import com.hf.commonmapper.result.PageResult;
import com.hf.commonmapper.result.Response;
import com.hf.commonmapper.vo.SpvScheDuleLogVo;
import java.util.List;
/**
* @Description:
* @Date: 2019/5/7
* @Auther:
*/
public interface SpvScheduleLogService {
List<SpvScheduleLog> queryAll();
/**
* 分页查询
* @param spvScheduleLogReq
* @return
*/
Response<PageResult<SpvScheDuleLogVo>> pageList(SpvScheduleLogReq spvScheduleLogReq);
}
实现类:
package com.hf.commonmapper.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hf.commonmapper.mapper.SpvScheduleLogMapper;
import com.hf.commonmapper.model.SpvScheduleLog;
import com.hf.commonmapper.model.SpvScheduleLogExample;
import com.hf.commonmapper.req.SpvScheduleLogReq;
import com.hf.commonmapper.result.PageResult;
import com.hf.commonmapper.result.Response;
import com.hf.commonmapper.service.SpvScheduleLogService;
import com.hf.commonmapper.utils.BeanUtils;
import com.hf.commonmapper.utils.CommonUtil;
import com.hf.commonmapper.utils.PropertiesCheckUtil;
import com.hf.commonmapper.vo.SpvScheDuleLogVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Description:
* @Date: 2019/5/7
* @Auther:
*/
@Slf4j
@Service
public class SpvScheduleLogServiceImpl implements SpvScheduleLogService {
@Autowired
private SpvScheduleLogMapper spvScheduleLogMapper;
@Override
public List<SpvScheduleLog> queryAll() {
SpvScheduleLogExample example = new SpvScheduleLogExample();
List<SpvScheduleLog> logs = spvScheduleLogMapper.selectByExample(example);
return logs;
}
@Override
public Response<PageResult<SpvScheDuleLogVo>> pageList(SpvScheduleLogReq spvScheduleLogReq) {
//校验分页参数
Response<String> response = PropertiesCheckUtil.autoCheck(spvScheduleLogReq);
if(response.isError()){
return Response.createError(response.getMsg());
}
//pagehelper使用
PageHelper.startPage(spvScheduleLogReq.getCurrPage(),spvScheduleLogReq.getPageSize());
//紧接着的第一个list会被分页
SpvScheduleLogExample example = new SpvScheduleLogExample();
List<SpvScheduleLog> logs = null;
try {
logs = spvScheduleLogMapper.selectByExample(example);
} catch (Exception e) {
log.error("<pageList> query data errot...{}",e);
return Response.createError("查询失败");
}
//获取到PageInfo
PageInfo<SpvScheduleLog> pageInfo = new PageInfo<>(logs);
//封装返回值
PageResult<SpvScheDuleLogVo> pageResult = new PageResult<>();
CommonUtil.setPageResult(pageResult,pageInfo);
List<SpvScheDuleLogVo> resultList = BeanUtils.collectionCopy(logs, SpvScheDuleLogVo.class);
pageResult.setList(resultList);
return Response.createSuccess("success",pageResult);
}
}
定义一个CommonUtil,转换分页结果:
package com.hf.commonmapper.utils;
import com.github.pagehelper.PageInfo;
import com.hf.commonmapper.result.PageResult;
/**
* @Description: 通用工具类
* @Date: 2019/5/7
* @Auther:
*/
public class CommonUtil {
public static void setPageResult(PageResult pageResult, PageInfo pageInfo) {
if(null == pageInfo){
return;
}
pageResult.setCurrPage(pageInfo.getPageNum());
pageResult.setPageSize(pageInfo.getPageSize());
pageResult.setTotalCount((int) pageInfo.getTotal());
pageResult.setHasMore(pageInfo.getPageNum() < pageInfo.getPages() ? true:false);
pageResult.setList(pageInfo.getList());
}
}
测试类:
package com.hf.commonmapper.service;
import com.hf.commonmapper.model.SpvScheduleLog;
import com.hf.commonmapper.req.SpvScheduleLogReq;
import com.hf.commonmapper.result.PageResult;
import com.hf.commonmapper.result.Response;
import com.hf.commonmapper.vo.SpvScheDuleLogVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* @Description:
* @Date: 2019/5/7
* @Auther:
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpvScheduleLogServiceTest {
@Autowired
private SpvScheduleLogService spvScheduleLogService;
@Test
public void queryAll(){
List<SpvScheduleLog> logs = spvScheduleLogService.queryAll();
System.out.println("这是啥:" + logs);
}
@Test
public void pageList(){
SpvScheduleLogReq logReq = new SpvScheduleLogReq();
logReq.setCurrPage(1);
logReq.setPageSize(3);
Response<PageResult<SpvScheDuleLogVo>> response = spvScheduleLogService.pageList(logReq);
PageResult<SpvScheDuleLogVo> data = response.getData();
System.out.println(data.getList().size());
}
}
可以看到测试结果:
好了,这篇博客先写到这里了!