Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapstruct: How to default a target String to Empty String when the Source is Null (Both fields have the same name and type) Java / Spring

Tags:

java

mapstruct

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

like image 221
MarcA Avatar asked Sep 20 '25 20:09

MarcA


1 Answers

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);

}
like image 62
Michael Avatar answered Sep 22 '25 10:09

Michael