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;
}
}
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