简体   繁体   English

Mapstruct:将集合映射到 object

[英]Mapstruct: mapping collection to object

I have a function like so:我有一个 function 像这样:

public HousesDTO mapHouses(Set<Home> roles) {
        HousesDTO homes = new HousesDTO();
        List<HouseDTO> dtos = new ArrayList<HouseDTO>();
        for (Home home : homes) {
            HouseDTO dto = new HouseDTO(home.getAddress(), home.getPrice());
            dtos.add(dto);
        }
          homes.setAllHomes(dtos);
          return homes;
        }
        return null;
    }

How can this be done using Mapstruct?如何使用 Mapstruct 做到这一点?

In case your HouseDTO has a parameterless constructor and setters for the values you can do it like this:如果你的HouseDTO有一个无参数的构造函数和值的设置器,你可以这样做:

@Mapper
public interface HousesMapper {
    default HousesDTO toHouses(Set<Home> homes) {
        HousesDTO housesDTO = new HousesDTO();
        housesDTO.setAllHomes(toHousesList(homes));

        return housesDTO;
    }

    List<HouseDTO> toHousesList(Set<Home> homes);
}

If the HouseDTO only has a constructor that expects the properties than there are three options left:如果HouseDTO只有一个期望属性的构造函数,则剩下三个选项:

  1. Wait for the MapStruct 1.4 release which will support instantiation by constructors等待支持构造函数实例化的 MapStruct 1.4 版本
  2. Create a default method where you map from Home to HouseDTO manually创建一个默认方法,您可以手动将 map 从HomeHouseDTO
  3. Create a Builder, see https://mapstruct.org/documentation/stable/reference/html/#mapping-with-builders创建 Builder,参见https://mapstruct.org/documentation/stable/reference/html/#mapping-with-builders

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM