使用 mapstruct 将 DTO 中的 DTO 映射到实体中的实体

Sru*_*ula 2 jhipster mapstruct

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

我正在使用 mapstruct 并且我已经有另一个实体映射器。

DTO

public class EntityDTO {

   private AnotherEntityDTO anotherEntityDTO;
   // other fields
}
Run Code Online (Sandbox Code Playgroud)
Entity

@Entity
public class Entity {
  private AnotherEntity anotherEntity;
  // other fields
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢。

Fil*_*lip 5

这实际上取决于您使用的是哪个版本的 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);

}
Run Code Online (Sandbox Code Playgroud)

另一种选择(如果您使用的版本低于 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);
}
Run Code Online (Sandbox Code Playgroud)

或者你可以定义一个新的映射AnotherEntityMapperAnotherEntity和使用@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);
}
Run Code Online (Sandbox Code Playgroud)

这实际上取决于您的用例。如果您需要在其他地方之间AnotherEntityAnotherEntityDTO上进行映射,我建议您使用新接口,以便您可以在需要的地方重用它