13

我如何将字符串映射到列表和列表到字符串?

考虑我们有以下课程

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
}

在 Dozer 和 Orika 中,我们可以使用以下代码行轻松映射

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

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

我如何在 MapStruct 中进行相同类型的映射?我在哪里可以找到更多关于 mapstruct 的示例?

4

2 回答 2

18

emailAddress下面的示例将列表中的元素映射PeopleTOprimaryEmailAddress和的secondaryEmailAddress属性中People

MapStruct 不能直接映射到集合中,但它允许您实现在映射后运行的方法以完成该过程。我使用了一种这样的方法将 的和primaryPhone属性secondaryPhone映射PeopleTOphones.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);
    }
}
于 2017-04-08T21:23:40.963 回答
2

我可以在这里看到一些例子:https ://github.com/mapstruct/mapstruct-examples

根据您的特定要求检查此模块(可迭代到非可迭代):https ://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-iterable-to-non-iterable

还有一个在这里:http: //blog.goyello.com/2015/09/08/dont-get-lost-take-the-map-dto-survival-code/

不确定是否可以将非迭代映射到迭代。

于 2016-05-10T16:41:36.150 回答