SourceObject
public class SourceObject {
public ArrayList<ListObject> list = new ArrayList<ListObject>();
public SourceObject() {
list.add(new ListObject());
}
}
listObject
public class ListObject {
public DetailsObject details = new DetailsObject();
public ListObject() {
details.forename="SourceForename";
details.surname="SourceSurname";
}
}
destinationObject
public class DestinationObject {
public DetailsObject details = new DetailsObject();
public DestinationObject() {
details.forename="DestinationForename";
details.surname="DestinationSurname";
}
}
Detailsobject
public class DetailsObject {
public String forename;
public String surname;
}
Mapper
@Mappings({
@Mapping(target="details.forename", source="list.get(0).details.forename"),
@Mapping(target="details.surname", source="list.get(0).details.surname"),
})
DestinationObject toDestination(SourceObject source);
如果我将详细信息直接放入sourceObject中,这将正常工作,但是当我尝试将其从列表中获取时,就会成为一个问题。我得到的错误是:
[错误]无法执行目标org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile(default-compile)项目模板上:编译失败:编译失败:[error] .../src/main/java/mapper/sourcetodestinationmap.java:[12,13]源参数(s)中不存在名为“ list.get(0).details.surname”的属性。您的意思是“ list.empty”?
[error] .../src/main/java/mapper/sourcetodestinationmap.java:[11,9]源参数(s)中不存在名为“ list.get(0).details.forename”的属性。您的意思是“ list.empty”?
Edit:映射器的当前状态:
@Mapper
public interface SourceToDestinationMap {
@Mapping(target = "details", source = "list")
DestinationObject toDestination(SourceObject source);
default DetailsObject map(List<ListObject> source) {
return map(source.get(0));
}
DetailsObject map(ListObject source);
}
由于您将bean属性和bean函数混合,您要尝试做的映射是不可能的。
您不能使用
@Mapping(source = "list.get(0).XXX")
.
。解决您的问题的方法是使用预选赛与
映射 - 拟合时间到非征用示例的方式相同的方式。或您可以提供自己的方法来执行映射。
@Mapper
public interface MyMapper {
@Mapping(target = "details", source = "list")
DestinationObject toDestination(SourceObject source);
default DetailsObject map(List<ListObject> source) {
return source != null && !source.isEmpty() ? map(source.get(0)) : null;
}
DetailsObject map(ListObject source);
}
然后,映射将生成正确的代码。
其他选择是使用@Mapping(expression="java()"
。
然后,您的映射器将看起来像:
@Mapper
public interface MyMapper {
@Mapping(target = "details.forename", expression = "java(source.list.get(0).details.forename)")
@Mapping(target = "details.surname", expression = "java(source.list.get(0).details.surname)")
DestinationObject toDestination(SourceObject source);
}
注意
expression
。 Mapstruct将按原样使用来自表达式的文本,并且不会执行任何验证检查。因此,它可能有点脆弱,因为不会有
null
和空的支票。
您还可以在sourceObject上创建一个“包装器”方法(getfirstelement):
public class SourceObject {
public ArrayList<ListObject> list = new ArrayList<ListObject>();
public SourceObject() {
list.add(new ListObject());
}
public getFirstElement(){
return list.get(0);
}
在您的初始映射中,您可以说:
@Mappings({
@Mapping(target="details.forename", source="firstElement.details.forename"),
@Mapping(target="details.surname", source="firstElement.details.surname"),
})
DestinationObject toDestination(SourceObject source);