需要添加以下依赖包:
<!-- 解决dto,do,vo转换问题 --> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.5.1</version> </dependency>
Java转换工具类如下:
import java.util.ArrayList; import java.util.List; import org.dozer.DozerBeanMapper; import org.dozer.Mapper; public class DtoEntityUtil { static Mapper mapper = new DozerBeanMapper(); public static <D,E> E trans(D t,Class<E> clazz){ if(t == null) return null; return mapper.map(t, clazz); } public static <D,E> List<E> trans(D[] ts,Class<E> clazz){ List<E> es = new ArrayList<E>(); if(ts == null) return es; for(D d:ts) { E e = (E)trans(d,clazz); if(e != null) es.add(e); } return es; } public static <D,E> List<E> trans(List<D> ts,Class<E> clazz){ List<E> es = new ArrayList<E>(); if(ts == null ) return es; for(D d:ts) { E e = (E)trans(d,clazz); if(e != null) es.add(e); } return es; } }
参考案例:
//下面两段代码是将entity转换成dto;分别是单个对象转换和集合对象转换;一般用于向consumer提供数据
//WorkeRecord是entity,从数据库中获取的对象
DtoEntityUtil.trans(workeRecord, WorkerRecordDTO.class);
//es是List集合,里面的对象是WorkeRecord的实例
List<WorkerRecordDTO> ds = (List<WorkerRecordDTO>)DtoEntityUtil.trans(es, WorkerRecordDTO.class);
//================华丽分隔符==================
//下面例子是dto转entity,一般用于向provider传入对象
DtoEntityUtil.trans(menuDto, Menu.class);//将mentDto转换成mentEntity List<User> users = DtoEntityUtil.trans(ts, User.class);//将dto集合ts转换成entityList users