MapStruct:从多个变量映射到一个集合

时间:2021-02-15 12:18:09

标签: mapstruct

我遇到了以下情况:

源类:

RESULT RECEIVED:  [{'study': '11111', 'project': 'AAAAA', 'details': []}, {'study': '22222', 'project': 'AAAAA', 'details': []}, 
{'study': '55555', 'project': 'BBBBB', 'details': []}, {'study': '66666', 'project': 'BBBBB', 'details': []}]

目标类:

public class OutcodeStats {
     double avgPrice;
     double avgPricePsf;
     double avgRent;
     double avgYield;
     double growth1y;
     double growth3y;
     double growth5y;
     String outcode;
     int salesPerMonth;
     int turnover;
     long effectiveDate;
}

我如何指示 mapStruct:

  • 将growth1y、growth3y 和growth5y 映射到数据中?
  • 忽略所有剩余字段

换句话说,如何使这个“伪”映射工作?

  public class GrowthStats {
    public String status;
    public String postcode;
    public String postcode_type;
    public String url;
    public List<List<Object>> data;
    public String process_time;
}

这是一个源类的例子:

   @Mapper
public interface OutcodeStatsMapper {

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

    @Mapping(source="outcode", target = "postcode")
    @Mapping(source = "growth1y", target = "data")
    @Mapping(source = "growth3y", target = "data")
    @Mapping(source = "growth5y", target = "data")
    GrowthStats outcodeStatsToGrowthStats(OutCodeStats stats);
}

这里是我希望在映射对象中看到的内容:

     "outcode":"BR1",
     "avg_price":436061.3,
     "avg_price_psf":0,
     "avg_rent":295.2,
     "avg_yield":"3.5%",
     "growth_1y":"5.6%",
     "growth_3y":"6.3%",
     "growth_5y":"17.9%",
     "sales_per_month":28,
     "turnover":"4%"

1 个答案:

答案 0 :(得分:0)

这是我让它工作的方式:

    @Mapper
public interface OutcodeStatsMapper {

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

    @Mapping(source = "outcode", target = "postcode")
    GrowthStats outcodeStatsToGrowthStats(OutCodeStats stats);

    @AfterMapping
    default void fillData(OutCodeStats outCodeStats, @MappingTarget GrowthStats growthStats) {
        growthStats.status = "success";
        growthStats.postcode_type= "outcode";
        growthStats.data = new ArrayList<>();
        Stream.of(outCodeStats.growth1y, outCodeStats.growth3y, outCodeStats.growth5y)
                .forEach(yearStats -> growthStats.data.add(List.of("null", "null", yearStats)));
    }
}