MapStruct String to List mapping

余生长醉 提交于 2019-12-05 14:23:49

问题


How would i map String to List and List to String?

Consider we have following classess

class People{
    private String primaryEmailAddress;
    private String secondaryEmailAddress;
    private List<String> phones;
    //getter and setters
}

class PeopleTO{
    private List<String> emailAddress;
    private String primaryPhone;
    private String secondaryPhone;
    //getter and setters
}

In Dozer and Orika, we can easily map with the following line of code

fields("primaryEmailAddress", "emailAddress[0]")
fields("secondaryEmailAddress", "emailAddress[1]")

fields("phones[0]", "primaryPhone")
fields("phones[1]", "secondaryPhone")

How i can do the same kind of mapping in MapStruct? Where would i find more examples on mapstruct?


回答1:


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);
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/37143179/mapstruct-string-to-list-mapping

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