0
点赞
收藏
分享

微信扫一扫

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


文章目录

  • ​​1. CopyUtil​​
  • ​​2. 使用案例​​
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;
}
}


举报

相关推荐

0 条评论