【问题标题】:How to perform a mapping with mapstruct that is dependant on more than one DTO variable如何使用依赖于多个 DTO 变量的 mapstruct 执行映射
【发布时间】:2022-01-20 07:07:15
【问题描述】:

我正在使用 mapstruct 将我的 DTO 映射到其对应的实体。

DTO 包含一个 Hashmap 变量,其条目应该映射到特殊 HashMap 实体的键和值变量。这就是为什么我用一个额外的方法来描述这个映射,如下所示:

@Mapper
public interface MyMapper {

      MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

      @Mapping(source = "myHashMap", target = "myHashMapEntityList", qualifiedByName = "mapMyHashMap")
      MyEntity mapToEntity(MyDTO dto);

      @Named("mapMyHashMap")
      static List<myHashMapEntity> mapMyHashMap(final Map<String, String> myHashMap) {
          ...
      }
}

这很好用。我唯一的问题是我不想映射哈希图的所有条目。我只想映射条目,其键包含在列表keysToBeMappedList 中。虽然可以从dto 构造此keysToBeMappedList,但此变量不是dto 的一部分。我想知道如何执行我的映射。

我的问题:

是否可以在这个MyMapper 接口中计算这个keysToBeMappedList,然后在mapMyHashMap 方法中使用这个列表?因为即使这是不可能的并且我将keysToBeMappedList 作为我的dto 的一部分,我仍然必须在mapMyHashMap 中同时使用keysToBeMappedListmyHashMap 来执行映射。而且我从未见过在这些 mapstruct 方法中使用了多个变量。

我希望我想做什么或多或少清楚。有人可以帮忙吗?

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    你可以使用表达式调用任何方法

      MyEntity mapToEntity(MyDTO dto, List<String> list);
    
    
    
     @Mapping(target = "name", expression = "java(mapMyHashMap(map, list))")
    

    否则,如果您不需要配置它,只需在方法中对其进行硬编码并进行过滤

    【讨论】:

      【解决方案2】:

      可以为方法添加更多参数:

      import org.mapstruct.Context;
      @Mapper
      public interface MyMapper {
      
            MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);
      
            @Mapping(source = "myHashMap", target = "myHashMapEntityList", qualifiedByName = "mapMyHashMap")
            MyEntity mapToEntity(MyDTO dto, @Context List<String> keysToBeMappedList);
      
            @Named("mapMyHashMap")
            static List<myHashMapEntity> mapMyHashMap(final Map<String, String> myHashMap, @Context List<String> keysToBeMappedList) {
                ...
            }
      }
      

      mapToEntity 方法的实现现在会将keysToBeMappedList 传递给mapMyHashMap 方法,但mapstruct 不会尝试将keysToBeMappedList 用于任何映射。

      You can find more information about the @Context here.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-13
        • 2020-07-07
        • 1970-01-01
        • 2021-05-18
        • 2020-09-12
        • 2023-03-23
        • 2017-09-17
        相关资源
        最近更新 更多