简体   繁体   中英

Mapstruct: mapping collection to object

I have a function like so:

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?

In case your HouseDTO has a parameterless constructor and setters for the values you can do it like this:

@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:

  1. Wait for the MapStruct 1.4 release which will support instantiation by constructors
  2. Create a default method where you map from Home to HouseDTO manually
  3. Create a Builder, see https://mapstruct.org/documentation/stable/reference/html/#mapping-with-builders

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.

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