Dto和Entity如何优雅的相互转换

什么是Dto,Entity,用来干什么?

    Dto data transfer object 数据传输实体,主要用于数据传输的实体模型;
    Entity 持久层的领域模型;
     当我在做分布式微服务的时候,通常是用Entity来做持久层的实体类,Dto来做接口传输的实体类。这个时候就有一个麻烦事,Entity和Dto的互转。通常的转换方法有两个途径,一个是通过反射的方式,来进行对象属性的复制;另一种是,通过硬编码进行对象属性的赋值;

1. 在service层中添加实体类转换函数
@Service
public MyEntityService {

  public SomeDto getEntityById(Long id){
    SomeEntity dbResult = someDao.findById(id);
    SomeDto dtoResult = convert(dbResult);
    // ... more logic happens
    return dtoResult;
  }

  public SomeDto convert(SomeEntity entity){
   //... Object creation and using getter/setter for converting
  }
}
2. 在各自的实体类中添加转换函数
public class SomeDto {

 // ... some attributes

 public SomeDto(SomeEntity entity) {
  this.attribute = entity.getAttribute();
  // ... nesting convertion & convertion of lists and arrays
 }

}

3. 通过反射的方式来进行,目前有common-beanutils,或者springframework的beanutils,或者modelmapper进行更复杂的定制。这样做得有点就是完全没有额外的编码负担,且通用性强;但是缺点是,性能很低(这里可能比硬编码的转换方式多上100倍时间左右)所以对于大数据量的转换,或者对反应时间敏感的场景,请不要使用;
ModelMapper modelMapper = new ModelMapper();
UserDTO userDTO = modelMapper.map(user, UserDTO.class);
4. 通过mapstruct在编译阶段,创建一个convert类,来进行转化,优点是自动代码生成,转换效率优良;缺点是虽然省略的硬编码,但是每个实体都需要写一个转换接口,着实不是很优雅。
@Mapper
public interface SheetConverter {

    @Mappings({})
    SheetDto sheetToSheetDto(Sheet sheet);

    @Mappings({})
    Sheet sheetDtoToSheet(SheetDto sheetDto);
}

原文地址:https://www.cnblogs.com/IC1101/p/11308317.html