【发布时间】:2019-11-12 16:09:08
【问题描述】:
我正在尝试使用 MapStruct 映射具有嵌套对象并需要外部变量的对象。
源 -> 目标映射是有损的,需要外部字符串
目标 -> 源映射工作并生成输出
我正在使用 Lombok,我的对象是不可变的。
//Entities
public class Repro {
@Value
@Builder
public static class Nested {
@NonNull
private String id;
@Nullable
private String version;
@NonNull
private String externalId;
}
@Value
@Builder
public static class SourceEntity {
@NonNull
private String id;
@NonNull
private String anotherId;
}
@Value
@Builder
public static class TargetEntity {
@NonNull
private Nested nested;
@NonNull
private String anotherId;
}
}
//Mapper
@Mapper
public interface ReproMapper {
@Mapping(target = "nested.version", ignore = true)
@Mapping(source = "source.id", target = "nested.id")
@Mapping(source = "source.anotherId", target = "anotherId")
@Mapping(source = "externalId", target = "nested.externalId")
Repro.TargetEntity fromSource(Repro.SourceEntity source, String externalId);
@Mapping(source = "nested.id", target = "id")
@Mapping(source = "anotherId", target = "anotherId")
Repro.SourceEntity fromTarget(Repro.TargetEntity target);
}
我收到错误消息(包名省略):
Can't map property "Repro.SourceEntity source" to "Repro.Nested nested". Consider to declare/implement a mapping method: "Repro.Nested map(Repro.SourceEntity value)
这告诉我要实现一个不可行的映射方法(因为它会构造一个部分 Nested 对象),该方法在 build() 调用期间会失败。
有没有办法使用 MapStruct 或者我只是实现自己的映射器?
【问题讨论】: