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对象转换显得比较繁琐!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值