javaList集合的两种赋值方式
写在之前
在开发中难免会有entity,vo,dto之间的转换那么如何优雅快速的进行转换呢?当然你可以get在set显然不推荐这样做!
对象转换
使用BeanUtils工具类copyProperties方法
像这样
//将merchantDTO赋值给entity(相同的属性) BeanUtils.copyProperties(merchantDTO,entity);
使用mapstruct转换
首先在项目中引入依赖
<!-- MapStruct代码生成器,对象转换 --> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </dependency>
新建接口
@Mapper//这里的mapper是包org.mapstruct.Mapper public interface AppCovert { AppCovert INSTANCE = Mappers.getMapper(AppCovert.class); /** * entity转dto */ AppDTO entityTodto(App entity); /** * dto转entity * @param dto * @return */ App dtoToEntity(AppDTO dto); }
注:使用泛型支持所有类型的List转换 使用
//将entity转换为dto MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.entityTodto(merchantInfo);
List转换
使用BeanUtils工具类
集合转换是不是也想使用copyProperties方法?对你想的没错,想对了一半 只不过要对copyProperties方法进行封装 像这样
/** * @param sources: 数据源类 * @param target: 目标类 * @return 赋值后的list */ public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target, BeanCopyUtilCallBack<S, T> callBack) { List<T> list = new ArrayList<>(sources.size()); for (S source : sources) { T t = target.get(); BeanUtils.copyProperties(source, t); list.add(t); } return list; }
使用
List<Merchant> entity = new ArrayList<>(); Merchant merchant = new Merchant(); entity.add(merchant); List<MerchantDTO> ts = BeanCopyUtil.copyListProperties(entity, MerchantDTO::new);
使用mapstruct转换
定义接口
@Mapper public interface AppCovert { AppCovert INSTANCE = Mappers.getMapper(AppCovert.class); /** * entityList转dtoList * @param app * @return */ List<AppDTO> listEntityToDto(List<App> app); }
使用
List<App> apps = new ArrayList<>(); List<AppDTO> appDtos = AppCovert.INSTANCE.listEntityToDto(apps);
对比BeanUtils工具类,mapstruct对象转换显得比较繁琐!