【问题标题】:ModelMapper - how calculate a value from source and set it to destinationModelMapper - 如何从源计算值并将其设置为目标
【发布时间】:2020-01-06 10:27:12
【问题描述】:

我正在尝试使用 ModelMapper 将源映射到目标。

在我的具体情况下,在源类中有一个属性(评论列表),我必须在其中按评分求和并将此值设置为目标类。

所以我尝试了转换器,但它不起作用。

        Converter<List<Review>, Double> sumReviewsRating = new AbstractConverter<List<Review>, Double>() {
        @Override
        protected Double convert(List<Review> reviews) {
            if(reviews!=null){
                return reviews.stream().mapToDouble(Review::getRating).sum();
                //it doesn't work also with return 1.0 for example;
            }else{
                return 0.0;
            }
        }
    };

 modelMapper.typeMap(MySource.class, MyDestination.class).addMappings(mapper ->{
            mapper.map(MySource::getCoverImageId, MyDestination::setImageUrl); //this works
            mapper.using(sumReviewsRating).map(MySource::getReviews, MyDestination::setRating);
        });

堆栈跟踪:

org.modelmapper.internal.ErrorsException: null
    at org.modelmapper.internal.Errors.toException(Errors.java:254) ~[modelmapper-2.3.6.jar:na]
    at org.modelmapper.internal.ReferenceMapExpressionImpl.map(ReferenceMapExpressionImpl.java:71) ~[modelmapper-2.3.6.jar:na]
    at org.modelmapper.internal.ConfigurableConditionExpressionImpl.map(ConfigurableConditionExpressionImpl.java:65) ~[modelmapper-2.3.6.jar:na]

如果我在转换器中设置断点,它不会进入。

我的赌注在哪里?

【问题讨论】:

  • 您的代码看起来不错。我想你只是有一些Review.rating=null?尝试添加检查。
  • @pirho 是的,我如何检查和忽略它们?
  • 请添加更多堆栈跟踪。它是否也曾进入转换器?你在你的问题中说:如果我在转换器中放置一个断点,它就不会进入

标签: java spring-boot modelmapper


【解决方案1】:

以下对我有用:

ModelMapper modelMapper = new ModelMapper();

Converter<List<String>, Double> sumReviewsRating = new AbstractConverter<List<String>, Double>() {
      @Override
      protected Double convert(List<String> reviews) {
        if(reviews!=null){
          return 1.0;
          //it work also with return 1.0 for example;
        }else{
          return 0.0;
        }
      }
    };

    modelMapper.typeMap(MySource.class, MyDestination.class).addMappings(mapper ->{
      mapper.using(sumReviewsRating).map(MySource::getReview, MyDestination::setRating);
    });

    MySource mySource = new MySource();
    mySource.setReview(Arrays.asList(new String[]{"1","2"}));
    MyDestination destination = modelMapper.map(mySource,MyDestination.class);

    System.out.println(destination.getRating());

@Getter @Setter
public class MyDestination {
  Double rating;
}


@Getter @Setter
public class MySource {
  List<String> review;
}

以上代码成功转换。

尝试像这样添加多个映射

**

typeMap.addMappings(mapper -> mapper.<String>map(Src::getA, Dest::setB))
          .addMappings(mapper -> mapper.<String>skip(Dest::setB))

**

【讨论】:

  • 是的,我在另一个项目中再次尝试过,它可以工作,但是如果我尝试我的方法,它就不起作用:-(我可以有一个更具体的错误而不是通用的 org.modelmapper .internal.ErrorsException ?
猜你喜欢
  • 1970-01-01
  • 2017-01-18
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
相关资源
最近更新 更多