I need to convert a list of items to a single dto item. In case there are any elements in the list, we take the first one. I implemented the converter interface this way, but it doesn't work. The destination item is null after the conversion.
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);
The entities on which I apply this converter look so:
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;
}
So I need the list of locations in Event to be converted into LocationDto in EventDto.
We can define a converter for each property mapping, that means we cam map locationList to location with custom converter.
With Java8
modelMapper.typeMap(Event.class, EventDto.class).addMappings(
mapper -> mapper.using(new LocationConverter()).map(Event::getLocationList, EventDto::setLocation));
With Java 6/7
modelMapper.addMappings(new PropertyMap() {
@Override
protected void configure() {
using(new LocationConverter()).map().setLocation(source.getLocationList());
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.