All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sinszm.sofa.util.PageFormatUtil Maven / Gradle / Ivy

Go to download

高可用服务框架,ORM数据操作组件 Copyright © 2021 智慧程序猿(sinsz.com) All rights reserved.

The newest version!
package com.sinszm.sofa.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.lang.reflect.Field;
import java.util.stream.Collectors;

/**
 * 分页数据格式化工具
 *
 * @author admin
 */
public class PageFormatUtil {

    /**
     * 计算指数
     *
     * @param response 响应
     * @param index    指数
     * @return long
     */
    private static  long calculateIndex(Page response, Integer index) {
        int currentIndex = (index == null ? 0 : index) + 1;
        return response.getCurrent() <= 1 ? currentIndex : currentIndex + (response.getCurrent() - 1) * response.getSize();
    }

    /**
     * 格式
     *
     * @param list           列表
     * @param clazz          clazz
     * @param indexFieldName 序号字段名
     * @return 分页数据
     */
    public static  Page format(Page list, Class clazz, String indexFieldName) {
        Page result = new Page<>(list.getCurrent(), list.getSize(), list.getTotal(),list.isSearchCount());
        result.setOrders(list.getOrders());
        result.setOptimizeCountSql(list.isOptimizeCountSql());
        result.setRecords(
                list.getRecords().stream()
                        .map(l -> {
                            T r = ReflectUtil.newInstance(clazz);
                            BeanUtil.copyProperties(l, r);
                            return r;
                        })
                        .peek(BaseUtil.consumerWithIndex((data, index) -> {
                            Field field = ReflectUtil.getField(clazz, indexFieldName);
                            if (field != null) {
                                field.setAccessible(true);
                                ReflectUtil.setFieldValue(data, field, calculateIndex(result, index));
                            }
                        }))
                        .collect(Collectors.toList())
        );
        return result;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy