How can you specify a defaultValue when mapping a DTO using MapStruct?
1 Option: Using expression
You can use expression
for more complex logic to set the default value or to handle cases where the attribute is a primitive type like boolean
.
@Mapping(target = "used", expression = "java(false)")
MyDTO toDto(MyEntity entity);
2 Option: Using defaultValue
To use defaultValue
in your case, change the target field type to Boolean
. This way MapStruct can use the provided default value when the source value is null or absent.
@Mapping(target = "used", defaultValue = "false")
MyDTO toDto(MyEntity entity);
3 Option: Using constant
If you want to set a fixed value regardless of the source is null or abset, you can constant
.
@Mapping(target = "used", constant = "false")
MyDTO toDto(MyEntity entity);