0

I'm using Immutables to generate some classes DTO classes, and Mapstruct to map JPA entities to DTOs. This works great, as long as the DTO has only required properties. If a property is not required (by making the accessor method return an Optional, as per the docs), the builder generated by Immutables will have a setter method with an Optional argument, which Mapstruct will fail on:

 error: Can't map property "java.lang.Integer id" to "java.util.Optional<java.lang.Integer> id". Consider to declare/implement a mapping method: "java.util.Optional<java.lang.Integer> map(java.lang.Integer value)".

Makes sense, thankfully there's an option available to also generate methods that take nullable arguments instead. This option generates an additional method that takes a nullable argument. However, Mapstruct seems to fail regardless of the presence of this method.

As a workaround, I implemented this abomination (but at this point I'd rather implement the mapping methods myself):

@Mapper
public class OptionalMapper {

    public <T> T unwrapOptional(final Optional<T> optional) {
        return optional.orElse(null);
    }

    public <T> Optional<T> wrapIntoOptional(final T value) {
        return Optional.ofNullable(value);
    }

Is there any way to make Mapstruct look for overloaded methods (or see the "correct" one first)? Am I going about this the wrong way or simply missing something? Thanks!

Steen
  • 311
  • 1
  • 3
  • 11

1 Answers1

0

Currently writing that custom OptionalMapper is the way to perform the unwrapping of the optionals.

I don't think that doing that is a bad thing. There is an open issue for supporting Optional

Filip
  • 19,269
  • 7
  • 51
  • 60
  • Hi Filip, thanks for your reply. My issue isn't so much that Mapstruct doesn't unwrap `Optional`s by itself, but more that it doesn't use the overloaded method that takes a nullable argument (which would negate the need for Mapstruct unwrapping `Optional`s). Is this a bug or am I doing something wrong? – Steen Apr 08 '21 at 09:26
  • I've misunderstood the question then. I think that you might be hit by [mapstruct/mapstruct/2377](https://github.com/mapstruct/mapstruct/issues/2377) – Filip Apr 08 '21 at 13:05