Mapstruct: Check for null for source before mapping to target. Require to throw a custom exception from mapstruct interface if the source is null.
Asked
Active
Viewed 3,102 times
1
-
Did you try @BeforeMapping? Link: [https://mapstruct.org/documentation/stable/api/index.html?org/mapstruct/BeforeMapping.html](https://mapstruct.org/documentation/stable/api/index.html?org/mapstruct/BeforeMapping.html) – Daimon Cool Jun 15 '20 at 17:44
2 Answers
2
This is currently not supported. However, you can write something like this by using the defaultExpression
.
Anyways, I would not suggest using MapStruct for this. Java Bean Validation is better suited for doing this.

Filip
- 19,269
- 7
- 51
- 60
1
I am little late to the party. Not sure if this is what you are/were looking for: Same idea as in @Filip answer, the following works for me (I am trying set a LocalDate type and throw if src is null):
The Mapper defines the fcn:
@Named("throwIfNull")
public <T> T throwIfNull(String fieldName) {
throw new RuntimeException("Field: '" + fieldName + "' is null but must not be.");
}
The mapping call looks as follows:
@Mapping(source = "renewalDate", target = "renewalDate", defaultExpression = "java(throwIfNull(\"renewalDate\"))")
(Notes:
- The src and target fields have the same name in my case)
- The "throwIfNull" is generic, so you need the @Named("throwIfNull"), else mapstruct will match on all fields which are String (since "throwIfNull" has a an input parameter of type String)

matze999
- 431
- 1
- 5
- 18