MapStruct String to List mapping

孤街醉人 提交于 2019-12-04 00:35:51

The example below maps elements from the emailAddress list in PeopleTO into the primaryEmailAddress and secondaryEmailAddress properties of People.

MapStruct can't directly map into collections, but it allows you to implement methods that run after a mapping to complete the process. I've used one such method for mapping the primaryPhone and secondaryPhone properties of PeopleTO into elements of the phones list in People.

abstract class Mapper {
    @Mappings({
        @Mapping(target="primaryEmailAddress", expression="emailAddress != null && emailAdress.size() >= 1 ? emailAdresses.get(0) : null"),
        @Mapping(target="secondaryEmailAddress", expression="emailAddress != null && emailAdress.size() >= 2 ? emailAdresses.get(1) : null"),
        @Mapping(target="phones", ignore=true)
    })
    protected abstract People getPeople(PeopleTO to);

    @AfterMapping
    protected void setPhones(PeopleTO to, @MappingTarget People people) {
        people.setPhones(new List<String>());
        people.getPhones().add(to.primaryPhone);
        people.getPhones().add(to.secondaryPhone);
    }
}

I could see some examples here: https://github.com/mapstruct/mapstruct-examples

Checkout this module for your specific requirement (Iterable to non-Iterable): https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-iterable-to-non-iterable

and another one here: http://blog.goyello.com/2015/09/08/dont-get-lost-take-the-map-dto-survival-code/

Not sure if it is possible to map the non-iterable to Iterable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!