我意识到这可能会让mapStruct超出它的设计目的,但万一我错过了一些东西......
我有一个 openapi-generator 生成的一组嵌套对象,这些对象都包装在 JsonNullable 中,用于
PATCH
端点(如果没有包装,java 无法区分显式设置为 null
的 json 属性和自此以来未定义的属性它们都映射到 java 的 null
)。我必须在 openapi 生成的 java 对象和 JPA 实体之间来回映射这些对象,并且 openapi 生成的对象和 JPA 实体之间的一些结构不是对称的。
我在
source
和 target
中使用点符号来处理非对称映射,并且效果很好,直到所有内容都包含在 JsonNullable 中。我不知道如何将嵌套和包装结合在一起@Mapping
。谷歌搜索了很多并搜索了 github 问题。尝试将其分解为多种映射方法,但也没有取得进展。考虑过自定义映射,但它看起来太复杂而难以维护。
我想做的事情的例子:
// My open-api-generator generated objects
class Thing {
JsonNullable<Thing2> thing2;
}
class Thing2 {
JsonNullable<Thing3> thing3
}
class Thing3 {
JsonNullable<String> myString;
}
---
class MyEntity {
String whereMyStringShouldGetMappedFrom;
}
---
class MyMapper {
@Mapping(source="whereMyStringShouldGetMappedFrom", target="thing.thing2.thing3") // <---- this doesn't work because each property is wrapped in JsonNullable
public abstract TopLevelThing mapIt(MyEntity myentity);
也许这会有所帮助。有点尴尬,但对我有用。
与 modelmapper 也能很好地配合
@Column(name="string_column",nullable = true, insertable = true, updatable = true)
String myString;
public JsonNullable<String> getMyString(){
return myString == null ? null : JsonNullable.of(myString);
}
public void setMyString(JsonNullable<String> arg){
this.myString = arg == null ? null : arg.orElse(null);
}
另一种选择是使用它,具体取决于您想要在结果中显示的内容以及您选择如何实施服务等:
@Column(name = "string_column", nullable = true, insertable = false, updatable = true)
@Setter
Boolean myString;
public JsonNullable<String> getMyString() {
return JsonNullable.of(myString);
}
您可以为这些情况添加自己的自定义转换器,如下所示:
final Converter<String, JsonNullable<String>> stringJsonNullableConverter = new AbstractConverter<>() {
@Override
protected JsonNullable<String> convert(final String source) {
if (source == null) {
return null;
}
return JsonNullable.of(source);
}
};
modelMapper.addConverter(stringJsonNullableConverter);
这样,每次需要将 String 映射到 JsonNullable 时,都会使用您的转换器。
您可以提供自定义映射方法来映射到 JsonNullable 或从 JsonNullable 映射。
public <Z> Z convertNullable(JsonNullable<Z> source) {
return source.get();
}
public <Z> JsonNullable<Z> convertNullable(Z source) {
if (source == null) {
return JsonNullable.undefined();
}
return JsonNullable.of(source);
}
还有一个条件映射,仅在存在 JsonNullable 时应用映射。
@Condition
public boolean shouldMapNullable(JsonNullable<?> source) {
return source.isPresent();
}