mapstruct/mapstruct-examples

Mapstruct defaultValue not working

lalkhum opened this issue · 2 comments

I have DTO

private String name = "name";

Mapper:

@Mapping(target = "name", defaultValue = "Mr Hello")

Default value gets set in my DB for null input but not for empty string "".

Does anyone know what's the issue here?

note: for Integer type and boolean type, the above Mapper defaultValue works for me.

oweis commented

Hi @lalkhum, defaultValue is used when the source property is null
to handle this case use:
@mapping(target = "name", source="name", qualifiedByName="mapName")

@Named("mapName")
default String mapName(String name) {
    if (name == null || name.equals("")) {
        return "Mr Hello";
    }
    return name;
}

PS: didnt try the code, but the fix is to use something near this

I guess with the latest versions of MapStruct the fix would be to define what a non present value is.

i.e. to use conditional mapping and define a custom @Condition.

e.g.

@Condition
public boolean isNotEmpty(String value) {
    return value != null && value.isNotEmpty();
}

MapStruct will then use this method to determine whether a string value is empty and if it is it will use the defined default value.

Closing this issue since the question has been answered.