Java 如何使用ModelMapper处理集合到列表的转换
我有以下课程:Java 如何使用ModelMapper处理集合到列表的转换,java,type-conversion,modelmapper,Java,Type Conversion,Modelmapper,我有以下课程: public class MyEntity { private Set<MyOtherEntity> other; } public class MyDTO { private List<MyOtherDTO> other; } 将PropertyMaps添加到ModelMapper会产生以下错误: 原因:org.modelmapper.ConfigurationException:modelmapper 配置错误: 1) 源方法java.ut
public class MyEntity {
private Set<MyOtherEntity> other;
}
public class MyDTO {
private List<MyOtherDTO> other;
}
将PropertyMaps
添加到ModelMapper
会产生以下错误:
原因:org.modelmapper.ConfigurationException:modelmapper
配置错误:
1) 源方法java.util.List.add()无效。确保该方法具有
零参数,不返回void
我想我不能在属性映射的配置中使用List.add()
那么,在ModelMapper
中实现列表到集合和向后转换的最佳方法是什么?属性映射必须使用它来映射属性。如果你使用不同的逻辑,它会抛出一个异常
因此,您有下一个选项(我将示例放在一个方向上,另一个方向是相同的):
选项1:确保PropertyMap与属性匹配
使用属性映射并确保ModelMapper将使用它,请查看以下规则:
- 标准:默认情况下
- 松散的
- 严格的
使用确保您的属性列表other
与目标属性other
匹配的属性。例如,如果您使用严格的策略,但顺序不正确,则该策略将不匹配
然后,如果您确定属性将匹配ModelMapper将按照其规则为您映射属性,或者如果您需要它,您将能够创建一个PropertyMap
,其中包含源MyTheEntity
和目标MyTherdTo
,并将其添加到ModelMapper
实例中
public class DTOToEntityPropertyMap extends PropertyMap<MyOtherEntity, MyOtherDTO> {
@Override
protected void configure() {
map().setPropertyOfOther(source.getPropertyOfOther());
//and so on...
}
}
modelMapper.addMappings(new DTOToEntityPropertyMap());
然后必须在父级属性映射中使用它,如下所示:
public class EntityToDTOPropertyMap extends PropertyMap<MyEntity, MyDTO> {
Converter<Set<MyOtherEntity> , List<MyOtherDto>> toOtherDto = new Converter<Set<MyOtherEntity> , List<MyOtherDto>>() {
public String convert(MappingContext<Set<MyOtherEntity> , List<MyOtherDto>> context) {
Set<MyOtherEntity> source = context.getSource();
List<MyOtherDto> destination = context.getDestination();
//Convert it using the logic you want (by hand for example)
return destination;
}
};
@Override
protected void configure() {
using(toOtherDto).map(source.getOther()).setOther(null);
}
}
Converter<Set<MyOtherEntity> , List<MyOtherDto>> toOtherDto = new Converter<Set<MyOtherEntity> , List<MyOtherDto>>() {
public String convert(MappingContext<Set<MyOtherEntity> , List<MyOtherDto>> context) {
Set<MyOtherEntity> source = context.getSource();
List<MyOtherDto> destination = context.getDestination();
//Convert it using the logic you want (by hand for example)
return destination;
}
};
public class EntityToDTOPropertyMap extends PropertyMap<MyEntity, MyDTO> {
Converter<Set<MyOtherEntity> , List<MyOtherDto>> toOtherDto = new Converter<Set<MyOtherEntity> , List<MyOtherDto>>() {
public String convert(MappingContext<Set<MyOtherEntity> , List<MyOtherDto>> context) {
Set<MyOtherEntity> source = context.getSource();
List<MyOtherDto> destination = context.getDestination();
//Convert it using the logic you want (by hand for example)
return destination;
}
};
@Override
protected void configure() {
using(toOtherDto).map(source.getOther()).setOther(null);
}
}
modelMapper.addMappings(new EntityToDTOPropertyMap());