问题描述
如何将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映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!