'Mapstruct: Check for null for source before mapping to target

Mapstruct: Check for null for source before mapping to target. Require to throw a custom exception from mapstruct interface if the source is null.



Solution 1:[1]

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.

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Filip
Solution 2