2
votes

I have two Objects Source and Target both with the same field names and types.

If a source field is null I would like the target to be "" (Empty String)

My Interface mapping looks like this (This is just two field, I have many)

@Mapper(componentModel = "spring", nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
public interface MyMapper {

@Mappings({
    @Mapping(target="medium", defaultExpression="java(\"\")"),
    @Mapping(target="origin", defaultExpression="java(\"\")")
 }) 
public Target mapFrom(Source source)

If the Source has a value it should be copied across, if it is null in the source it should be "" in the target.

Mapstruct-1.3.0 seems to just keep everything null.

Any Idea? I would like default to be empty String for everything

1
Little offtopic from me: you can set default componentModel to "spring" for all of your mappers, hence no need to explicitly set it in @Mapper annotation. Refer to mapstruct.org/documentation/stable/reference/html/… - Nikolai Shevchenko

1 Answers

3
votes

You need to set the NullValuePropertyMappingStrategy (as part of the Mapper annotation) for defining how null properties are to be mapped.

See NullValuePropertyMappingStrategy.html#SET_TO_DEFAULT

The default value for String is "". You don't need to define it explicitly.

So, your mapper can simply look like this:

@Mapper(
    componentModel = "spring", 
    nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT, 
    nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT
)
public interface MyMapper {

    public Target mapFrom(Source source);

}