【问题标题】:Choice the right source during mapping with mapstruct在使用 mapstruct 映射期间选择正确的源
【发布时间】:2021-10-05 00:43:48
【问题描述】:

我想与大家讨论解决这个问题的最佳方法。 我有一个像这样的java对象,它是一个源代码

public class Source{
  private String customValue;
  private List<String> listOfCustomValues;
  
  //etc
}

当然,我有一个目标 java 对象

public class Target{
  private String ownCustomValue;
        
  //etc
}

现在,我会以这种方式(或类似的方式)进行映射

@Mapper
public abstract class MapperSourceToTarget {
  @BeanMapping(ignoreByDefault = true)
  @Mapping(target = "ownCustomValue", qualifiedByName = "customMapping")
  public abstract Target fromSourceToTarget ( Source source);

@Named("customMapping")
public String toFuelType(Source source) {
  String firstValue = source.getListOfCustomValues().get(0);
  return ( firstValue.isEmpty() || firstValue == null ) ? source.getCustomValue() : firstValue;
  }

}

您对这种行为有什么建议或批评吗?我可以用更好的方式做到这一点吗?

【问题讨论】:

    标签: java mapping mapstruct


    【解决方案1】:

    当目标映射需要从多个属性或列表中派生时,问题中的方法是最好的方法。

    @Mapper
    public abstract class MapperSourceToTarget {
    
        @BeanMapping(ignoreByDefault = true)
        @Mapping(target = "ownCustomValue", qualifiedByName = "customMapping")
        public abstract Target fromSourceToTarget ( Source source);
    
        @Named("customMapping")
        public String toFuelType(Source source) {
            String firstValue = source.getListOfCustomValues().get(0);
            return ( firstValue.isEmpty() || firstValue == null ) ? source.getCustomValue() : firstValue;
      }
    }
    

    这样做可以让您完全控制您想要映射您的财产的方式

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2018-09-15
      • 2022-11-09
      • 2018-08-18
      • 2021-04-25
      相关资源
      最近更新 更多