在java开发过程中,经常会有po(数据库实体)转vo(返回实体)的操作,可以使用对应的复制类工具:
- BeanUtils(spring或者jdk的)
- dozerMapper
- orika
在集合复制上,没有现成的工具可以使用
- 下面我们在BeanUtils(spring包下)的工具类下实现对集合的复制功能
public class BeanListUtils extends BeanUtils {
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> targetSupplier) {
if (null == sources || null == targetSupplier) {
return null;
}
return sources.stream().map(s -> {
T target = targetSupplier.get();
copyProperties(s, target);
return target;
}).collect(Collectors.toList());
}
public static <S, T> IPage<T> copyPage(IPage<S> sources, IPage<T> target, Supplier<T> targetSupplier) {
BeanUtils.copyProperties(sources, target);
target.setRecords(copyListProperties(sources.getRecords(), targetSupplier));
return target;
}
}
使用方法:
List<S> targetList = new ArrayList<>();
List<T> sourceList= BeanListUtils.copyListProperties(targetList, T::new);
IPage<S> targetPage = baseMapper.selectPage(new Page<>(page, limit), queryWrapper);
IPage<T> sorecePage = BeanListUtils.copyPage(targetPage, new Page<>(), T::new);