How to specify a default value for a boolean field using MapStruct
Asked Answered
G

2

12

How can you specify a defaultValue when mapping a DTO using MapStruct? The following constructs did not work

@Mapping(target = "used", defaultValue = "0")
MyDTO toDto(MyEntity entity);

@Mapping(target = "used", defaultValue = "false")
MyDTO toDto(MyEntity entity);

The documentation shows examples for all types except booleans

Glossitis answered 26/12, 2019 at 6:19 Comment(1)
What does it didn't work mean? How didnthe generated code look like? What did you expect it to look like?Franci
W
27

To be able to use defaultValue, you must specify a source. If the source is null then it will use the defaultValue defined.

To always assign a specific value to the target, in your case zero or false, you should then use constant instead.

More info on Default values and constants

Wroth answered 29/12, 2019 at 15:25 Comment(1)
Using constant directive worked for me. MapStruct is able to convert to actual type specified as a String value. e.g. used is assigned as false if it is of type boolean. ``` @Mapping(target = "used", constant = "false") MyDTO toDto(MyEntity entity); ```Pelecypod
C
1

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);
Champaign answered 4/8 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.