【问题标题】:Mapping a DTO in a DTO to entity in entity with mapstruct使用 mapstruct 将 DTO 中的 DTO 映射到实体中的实体
【发布时间】:2017-09-17 00:28:35
【问题描述】:

我有一种情况,我在 DTO 中有另一个 DTO,我必须映射到其对应的实体。

我正在使用 mapstruct,并且已经存在 AnotherEntityMapper。

DTO

public class EntityDTO {

   private AnotherEntityDTO anotherEntityDTO;
   // other fields
}

Entity

@Entity
public class Entity {
  private AnotherEntity anotherEntity;
  // other fields
}

如何更改EntityMapper接口,以便我可以将anotherEntityDTO映射到anotherEntity?

谢谢。

【问题讨论】:

    标签: jhipster mapstruct


    【解决方案1】:

    这真的取决于您使用的是哪个版本的 MapStruct。如果您使用的是 1.2.0.Beta 或更高版本,您可以在 EntityMapper 接口上定义嵌套属性:

    @Mapper
    public interface EntityMapper {
    
        @Mapping(target = "anotherEntity", source = "anotherEntityDTO")
        @Mapping(target = "anotherEntity.propE", source = "anotherEntityDTO.propD")
        Entity map(EntityDDTO dto);
    
    }
    

    另一个选项(如果您使用低于 1.2.0.Beta 的版本,则必须这样做)是在您的 EntityMapper 中添加一个新方法,例如:

    @Mapper
    public interface EntityMapper {
    
        @Mapping(target = "anotherEntity", source = "anotherEntityDTO")
        Entity map(EntityDDTO dto);
    
        @Mapping(target = "propE", source = "propD")
        AnotherEntity map(AnotherEntityDTO);
    }
    

    或者您可以为AnotherEntity 定义一个新的映射器AnotherEntityMapper 并使用@Mapper(uses = {AnotherEntityMapper.class})

    @Mapper
    public interface AnotherEntityMapper {
    
        @Mapping(target = "propE", source = "propD")
        AnotherEntity map(AnotherEntityDTO);
    }
    
    @Mapper(uses = {AnotherEntityMapper.class}
    public interface EntityMapper {
    
        @Mapping(target = "anotherEntity", source = "anotherEntityDTO")
        Entity map(EntityDDTO dto);
    }
    

    这真的取决于您的用例。如果你需要在其他地方做AnotherEntityAnotherEntityDTO之间的映射,我建议你使用一个新的接口,这样你就可以在需要的地方重复使用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2021-12-31
      相关资源
      最近更新 更多