How to ignore empty strings when mapping in Mapster?
In MapStruct, you can use the NullValueMappingStrategy and Expression annotations to ignore mapping empty strings.
Firstly, add the nullValueMappingStrategy annotation to your Mapper interface or class and set its value to NullValueMappingStrategy.RETURN_DEFAULT. This will instruct MapStruct to ignore empty strings during the mapping process.
For example:
@Mapper(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
public interface MyMapper {
// 映射方法
}
Next, add an Expression annotation to the properties where empty strings need to be ignored, and use a SpEL expression to specify a condition for mapping empty strings to a default value.
For example, if you have a property named “name” and you want to ignore empty strings during mapping, you can do the following:
@Mapping(target = "name", source = "name", qualifiedByName = "ignoreEmptyString")
DestinationObject map(SourceObject source);
@Named("ignoreEmptyString")
default String ignoreEmptyString(String value) {
return value.isEmpty() ? null : value;
}
In the example above, we used the qualifiedByName attribute in the @Mapping annotation of the mapping method and specified it as “ignoreEmptyString”. We then added a default method named ignoreEmptyString in the Mapper interface, which takes a string parameter and returns a string. In this method, we implemented a condition that returns null if the string is empty, otherwise it returns the original string.
In this way, MapStruct will determine whether to map empty strings to default values based on the logic of the ignoreEmptyString method.