MapStruct String to List映射 [英] MapStruct String to List mapping

查看:2862
本文介绍了MapStruct String to List映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将String映射到List和List to String?

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

考虑我们有以下classess

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
}

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

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")

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

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

推荐答案

以下示例映射来自 emailAddress的元素列入 PeopleTO 进入 primaryEmailAddress secondaryEmailAddress 属性

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

MapStruct无法直接映射到集合,但它允许您实现方法在映射完成该过程后运行。我使用了一种这样的方法来映射 PeopleTO的 primaryPhone secondaryPhone 属性手机列表的元素。

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

这篇关于MapStruct String to List映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆