mapstruct / mapstruct-examples

Examples for using MapStruct
Other
1.28k stars 511 forks source link

Mapstruct defaultValue not working #132

Closed lalkhum closed 1 year ago

lalkhum commented 2 years ago

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 1 year ago

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

filiphr commented 1 year ago

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.