我有一个简单的类,我想使用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
}
Run Code Online (Sandbox Code Playgroud)
我想将这些转换为包含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
}
Run Code Online (Sandbox Code Playgroud)
如果我删除我的物品列表和ThingsDTO列表,那么modelmapper是一个令人愉快的使用,
modelMapper.map(source, SourceDTO.class);
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何让映射器将事物列表转换为ThingDTO列表.从文档中,我认为我需要创建一个扩展PropertyMap的mapper类,但我无法弄清楚如何配置它.
欢迎提供相关文档的任何指示
我认为如果你将ModelMapper配置为LOOSE或STANDARD它会为你做.
modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
Run Code Online (Sandbox Code Playgroud)
其他你可以尝试下一个:
您可以创建一个转换器,如:
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;
}}
Run Code Online (Sandbox Code Playgroud)然后自定义一个映射到ThingDTO的东西:
public class SourceToSourceDTOMap extends PropertyMap<Thing, ThingDTO> {
@Override
protected void configure(){
using(new ListThingToThingDTOConverter()).map(source.getThings()).setThings(null);
}
Run Code Online (Sandbox Code Playgroud)最后,您必须将SourceToSourceDTOMap添加到ModelMapper中,如下所示:
modelMapper = new ModelMapper();
modelMapper.addMappings(new SourceToSourceDTOMap());
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
9404 次 |
| 最近记录: |