关键词搜索

源码搜索 ×
×

list和对象数据复制CopyUtil工具类

发布2021-04-13浏览1322次

详情内容

1. CopyUtil
package com.gblfy.wiki.util;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gblfy
 * @desc list和对象数据复制
 * @date 2021-04-13
 */
public class CopyUtil {

    /**
     * 单体复制
     */
    public static <T> T copy(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }

        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BeanUtils.copyProperties(source, obj);
        return obj;
    }

    /**
     * 列表复制
     */
    public static <T> List<T> copyList(List source, Class<T> clazz) {
        List<T> target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)) {
            for (Object c : source) {
                T obj = copy(c, clazz);
                target.add(obj);
            }
        }
        return target;
    }
}

    2. 使用案例
    package com.gblfy.wiki.service;
    
    import com.gblfy.wiki.entity.Ebook;
    import com.gblfy.wiki.entity.EbookExample;
    import com.gblfy.wiki.mapper.EbookMapper;
    import com.gblfy.wiki.req.EbookQueryReq;
    import com.gblfy.wiki.resp.CommonResp;
    import com.gblfy.wiki.resp.EbookQueryResp;
    import com.gblfy.wiki.util.CopyUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.util.ObjectUtils;
    
    import java.util.List;
    
    @Service
    public class EbookServiceImpl {
    
        @Autowired
        private EbookMapper ebookMapper;
    
        public List<EbookQueryResp> list(EbookQueryReq req) {
            EbookExample example = new EbookExample();
            EbookExample.Criteria criteria = example.createCriteria();
            if (!ObjectUtils.isEmpty(req.getName())) {
                criteria.andNameLike("%" + req.getName() + "%");
            }
            List<Ebook> ebookList = ebookMapper.selectByExample(example);
            //集合数据复制 使用案例
            List<EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);
            //对象数据复制 使用案例
            Ebook ebook = CopyUtil.copy(req, Ebook.class);
            return list;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    相关技术文章

    点击QQ咨询
    开通会员
    返回顶部
    ×
    微信扫码支付
    微信扫码支付
    确定支付下载
    请使用微信描二维码支付
    ×

    提示信息

    ×

    选择支付方式

    • 微信支付
    • 支付宝付款
    确定支付下载