首页 > 解决方案 > 模型映射器计算

问题描述

我正在尝试ModelMapper在映射过程中使用来计算属性。这是可能的,因为它没有像我预期的那样工作。

PropertyMap<com.fmg.myfluent.domain.Quote, ClientQuote> personMap = new     
    PropertyMap<com.fmg.myfluent.domain.Quote, ClientQuote>() {
       protected void configure() {
          map().setTotalLoan(source.getTotalPayable());
          // monthlyRate NOT Working!
          map().setMonthlyRate((source.getAnnualRate()/12));
       }
    };

我期望月率是年率/12。但是,月率设置为年率而不进行计算。

预计:

 Annual Rate = 12, Monthly Rate: 1

实际的:

Annual Rate = 12, Monthly Rate: 12

标签: javamodelmapper

解决方案


您需要添加一个手动转换器来转换一个值ModelMapper

Converter<Integer, Integer> annualToMonthlyConverter = ctx -> ctx.getSource() == 0 ? 0 : ctx.getSource() / 12;

现在使用此转换器将您的源年度字段转换为您的目标每月字段

PropertyMap<Source, Target> personMap = new
            PropertyMap<Source, Target>() {
                protected void configure() {
                    map().setAnnual(source.getAnnual());

                    using(annualToMonthlyConverter).map(source.getAnnual(), destination.getMonthly());
                }
            };

笔记:

只是一个想法,根据您的设计,您也可以只映射源的年度字段,然后annual/12从目标类的monthly吸气剂返回

public int getMonthly() {
    return annual / 12;
}

推荐阅读