![](/img/trans.png)
[英]Is there a way to map an empty String to null using MapStruct?
[英]Map null values to default using builder with MapStruct
我想將字段從Source
映射到Target
類,如果源值為null
,我想根據數據類型將其轉換為默認值("" 表示字符串,0 表示數字類型等)。 為了設置值,我沒有使用常規的 setter,而是使用 builder(使用protobuf ,因此方法的名稱是newBuilder()
和build()
)。
class Source {
private final String value; // getter
}
class Target {
private final String value;
public static Builder newBuilder() {return new Builder()}
public static class Builder {
public static setValue() {/*Set the field*/}
public static Target build() {/*Return the constructed instance*/}
}
我的映射器看起來像這樣:
@Mapper(
nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT,
nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT
)
public interface TargetMapper {
Target map(Source source);
}
使用此代碼生成的映射器實現調用target.setValue(source.getValue())
,而不是執行 null 檢查並在 source 返回null
設置默認值。 有趣的是,當我向map
方法添加以下注釋時,實現中存在空檢查。
@Mapping(source="value", target="value", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT)
這是帶有構建器的 MapStruct 中的錯誤,還是我缺少一些配置以能夠將空映射設置為默認策略,而不是在所有字段映射上復制它?
編輯:出於某種原因,將nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS
添加到類級別@Mapper
注釋會添加空檢查,但沒有顯式設置值,只是跳過對setValue
的調用。 對於 protobuf,這沒問題,因為此功能在庫中,但對於其他實現,該字段將保持為空。
@Mapping(source="value", target="value", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT)
適用於更新方法(因此具有@MappingTarget
注釋參數的方法
常規方法沒有真正的對應物: 1. NullValueMappingStragegy
適用於 bean 參數本身。 2. NullValueCheckStragegy
確實對 bean 屬性執行檢查,但不返回默認值。
命名並不是真正的輝煌,它有着悠久的歷史。 我們仍然打算在某一天調整這一點。
一種解決方案是使用對象工廠創建構建器目標對象並使用默認值預填充它,然后讓 MapStuct 有一天覆蓋這些。
也許你可以這樣做:
@Mapper(
// to perform a null check
nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS
)
public interface TargetMapper {
Target map(Source source);
}
// to create a pre-defined object (defaults set a-priori). Not sure
// whether this works with builders.. just try
@ObjectFactory
default Target.Builder create() {
Target.Builder builder = Target.newBuilder();
builder.setValueX( "someDefaultValue" );
return builder;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.