java - 将项目列表转换为单个对象

标签 java mapping modelmapper

我需要将项目列表转换为单个 dto 项目。如果列表中有任何元素,我们将采用第一个元素。 我用这种方式实现了转换器接口(interface),但是不起作用。转换后目标项为空。

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。

最佳答案

我们可以为每个属性映射定义一个转换器,这意味着我们可以使用自定义转换器将 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());
    }
});

关于java - 将项目列表转换为单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50871553/

相关文章:

java SSLHandshakeException 一般 SSLEngine

java - java抽象类和接口(interface)最佳实践

java - Hibernate 和 MappingNotFoundException

java - 为什么在 Controller 中使用 @GetMapping 而不是 @DeleteMapping 进行删除工作?

python - 将部分案例匹配到 Python 字典

java - 使 JPA 和 ModelMapper 在实体更新中工作

java - 使用 Spring Data 将两个对象合并到 Map

java - Spring MVC多个ModelAttribute在同一个表单上

java - 使用自定义方法为 ModelMapper 定义映射

java - ModelMapper:如何映射作为泛型传递的 List<String>?