BeanUtil.copyProperties对象转换比较

日常开发中,涉及到DO、DTO、VO对象属性拷贝赋值,需要大量重复set很浪费时间,为了提高效率找了一些方法

传统的get/set方法

public PersonDTO personToPersonDTO(Person person) {
    if (person == null) {
        return null;
    }PersonDTO personDTO = new PersonDTO();
    personDTO.setName(person.getName());
    personDTO.setAge(person.getAge());return personDTO;
}

这种方式执行效率高,但是如果字段很多的情况下肯定是很费时,影响我们的开发效率

使用BeanUtil.copyProperties

 for (AccountInfoDto accountInfoDto : accountInfoList) {
            NoCashDirectLinkAccount noCashDirectLinkAccount = new NoCashDirectLinkAccount();
            BeanUtils.copyProperties(accountInfoDto,noCashDirectLinkAccount);
            noCashDirectLinkAccount.setStatus(StatusEnum.InsertOrdinal());
            noCashDirectLinkAccount.setId(IdUtils.setNextStrId("NoCashDirectLinkAccount"));

            directLinkAccounts.add(noCashDirectLinkAccount);
        }

BeanUtils.copyProperties的底层原理是使用反射机制,将源对象的属性值复制到目标对象的对应属性中,不过方便
使用反射运行效率肯定是不高,而且还有些坑

  1. 字段类型和名字需要完全一样
  2. 使用lombok的话包装类和非包装类也无法进行转换
  3. 只是浅拷贝

使用映射工具库

如MapStruct、ModelMapper等

    @Mapper  
    public interface SourceTargetMapper {  
    SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);  

    @Mapping(source = "name", target = "name")  
    @Mapping(source = "age", target = "age")  
    Target mapToTarget(Source source);  
    }  

    //使用
    Target target = SourceTargetMapper.INSTANCE.mapToTarget(source);

这种底层原理等同于get/set,但也要创建配置类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值