Skip to content

Respect only explicit mappings but fail on unmapped source fields #3574

@thiko

Description

@thiko

Use case

Imagine a PATCH request with several JsonNullable fields.

class MyDto {
  private JsonNullable<String> firstname;
  private JsonNullable<String> surname
}

The mapper should overwrite present fields only:

@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
        unmappedSourcePolicy = ReportingPolicy.ERROR)
interface MyPartialUpdateMapper {

  @Mapping(source = "firstname", target = "firstname", conditionExpression = "java(updatedContent.getFirstname().isPresent())")
  @BeanMapping(ignoreByDefault = true)
  void updateMyDomainObject(@MappingTarget MyDomainObject domain, MyDto updatedContent);

  default <T> T fromJsonNullable(JsonNullable<T> nullableValue) {
      if(nullableValue.isPresent()) {
          return nullableValue.get();
      }
      return null;
  }
}

The @BeanMapping(ignoreByDefault = true) is used to ensure that only those fields in the domain object that are set in the Patch-DTO are overwritten. Unfortunately, the unmappedSourcePolicy = ReportingPolicy.ERROR is ignored in this case.

As far as I can see, there is no way to enforce explicit mapping and cause the build to fail if one of the mappings is forgotten. This feature would make the mappings much better maintainable in such situations.

Generated Code

No response

Possible workarounds

No response

MapStruct Version

1.5.3.Final

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions