我有一个简单的类,我想使用modelMapper映射到DTO类。
class Source {
private String name;
private String address;
List<Thing> things;
// getters and setters follows
}
class Thing {
private String thingCode;
private String thingDescription;
// getters and setters
}
我希望将这些转换为包含ThingDTO列表的sourceDTO,例如
class sourceDTO {
private String name;
private String address;
List<ThingDTO> things;
// getters and setters.
}
class ThingDTO {
private String thingCode;
private String thingDescription;
// getters and setters
}
如果我删除了物品清单和物品清单DTO,那么模型选择器是一种使用的乐趣,
modelMapper.map(source, SourceDTO.class);
但我无法弄清楚如何让映射器将事物列表转换为ThingDTO列表。从文档中,我想我需要创建一个扩展PropertyMap的mapper类,但我无法弄清楚如何配置它。
欢迎任何指向相关文档的指示
答案 0 :(得分:6)
我认为如果你将ModelMapper配置为LOOSE或STANDARD它会为你做。
modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
其他你可以尝试下一步:
您可以创建一个转换器,如:
public class ListThingToThingDTOConverter implements Converter<List<Thing>, List<ThingDTO>> {
@Override
public List<ThingDTO> convert(MappingContext<List<Thing>, List<ThingDTO>> context) {
List<Thing> source = context.getSource();
List<ThingDTO> output = new ArrayList<>();
...
//Convert programmatically List<Thing> to List<ThingDTO>
...
return output;
}}
然后自定义ThingDTO的Mapping Thing:
public class SourceToSourceDTOMap extends PropertyMap<Thing, ThingDTO> {
@Override
protected void configure(){
using(new ListThingToThingDTOConverter()).map(source.getThings()).setThings(null);
}
最后,您必须将SourceToSourceDTOMap添加到ModelMapper中,如下所示:
modelMapper = new ModelMapper();
modelMapper.addMappings(new SourceToSourceDTOMap());
答案 1 :(得分:0)
您可以通过创建泛型来映射以下代码。参考链接
http://modelmapper.org/user-manual/generics/
进口:
import java.lang.reflect.Type;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
在您的服务或控制器类别中:
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<SourceDTO>(){}.getType();
SourceDTO sourceDTO = modelMapper.map(source,listType);