我需要将项目列表转换为单个dto项目。如果列表中有任何元素,我们将采用第一个元素。 我用这种方式实现了转换器接口,但它不起作用。转换后目标项为空。
public class LocationConverter implements Converter<List<Location>,LocationDto> {
@Override
public LocationDto convert(MappingContext<List<Location>, LocationDto> mappingContext) {
ModelMapper modelMapper = new ModelMapper();
List<Location> locations = mappingContext.getSource();
LocationDto locationDto = mappingContext.getDestination();
if (locations.size() >= 1) {
Location location = locations.get(0);
modelMapper.map(location, locationDto);
return locationDto;
}
return null;
}
}
ModelMapper modelMapper = new ModelMapper();
modelMapper.addConverter(new LocationConverter());
Event event = new Event();
modelMapper.map(event, eventDto);
我应用此转换器的实体看起来如此:
public class Event extends BasicEntity {
private Integer typeId;
private String typeName;
private List<Location> locationList;
}
public class EventDto {
private Integer typeId;
private String typeName;
private LocationDto location;
}
所以我需要将Event中的位置列表转换为EventDto中的LocationDto。
答案 0 :(得分:2)
我们可以为每个属性映射定义一个转换器,这意味着我们将locationList映射到具有自定义转换器的位置。
使用Java8
modelMapper.typeMap(Event.class, EventDto.class).addMappings(
mapper -> mapper.using(new LocationConverter()).map(Event::getLocationList, EventDto::setLocation));
使用Java 6/7
modelMapper.addMappings(new PropertyMap() {
@Override
protected void configure() {
using(new LocationConverter()).map().setLocation(source.getLocationList());
}
});