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 thedocs ), 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!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.