当前位置: 首页 > 知识库问答 >
问题:

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

郑旭
2023-03-14

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

我正在使用mapstruct,我已经有antherEntityMapper已经存在。

DTO

public class EntityDTO {

   private AnotherEntityDTO anotherEntityDTO;
   // other fields
}
Entity

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

如何更改EntityMapper接口,以便我可以将一个另一个EntityDTO映射到另一个Entity?

谢谢

共有1个答案

公孙盛
2023-03-14

这实际上取决于您使用的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);
}

或者您可以为antherEntity定义一个新的MapperantherEntityMapper并使用@Mapper(使用={antherEntityMapper.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);
}

这取决于你的用例。如果您需要在AnotherityAnotherEntityDTO之间进行映射,我建议您使用一个新的接口,以便在需要的地方重用它

 类似资料:
  • 我正在尝试使用AutoMapper在LLBLGen实体和DTO之间创建映射。 我的DTO如下所示: ParentEntity包含一个与DTO列表同名的ChildCollection和一个Id(需要忽略其他LLBL字段)。因此,当ParentEntity映射到父d to时,它也应该将ChildCollection映射到一个子列表。 这就是我到目前为止得到的: 这会导致Id被映射,但List的计数为0

  • 我不熟悉Mapstruct,在特定用例中遇到问题 因此,如果我的来源属性hotmail.com我的目标属性应该收到“个人”,如果我的来源facebook.com我的目标应该收到“公司”。 我想用表达法,但没法绕过它。我该怎么做?

  • 我希望在我正在从事的一个项目中使用CQR,但是我目前正在努力寻找实现CQR查询端的最佳方法。基于我有限的理解,有一个瘦数据层(有时称为瘦读取层),用于查询数据库并返回DTO,其中包含应用程序UI层使用的查询结果。 由于这是一个Java的EE应用程序,我正在开发薄数据层,使用JPA使用EntityManager.createNamedQuery查询数据库,返回一个包含结果的实体,然后将其映射到DTO

  • 问题内容: 我正在使用 MapStruct 进行映射。相同的映射器用于从dto 创建 和 更新 实体。完成dto的id验证,以了解是否必须创建一个新实体(id == null)还是应该从数据库中检索它(id!= null)。 我实际上正在使用MapperDecorator作为解决方法。范例: 映射器 装饰器 但是,由于必须为每个映射器创建一个装饰器,因此该解决方案变得繁重。 有什么好的解决方案吗?

  • 问题内容: 我们将使用DTO在表示层之间来回发送数据。我们有像这样的图层: facade appService domain 并且我们使用推土机来帮助我们将实体转换为dto。但是我现在有两个问题: 从实体到dto,我们可以使用推土机,但是从dto到实体,我们可以使用推土机吗?如果是,如何? 我应该在哪里创建实体?在外观或DTOAssembler中? 例如,我必须注册一本书。这本书的实体外观如下: