【发布时间】: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