Use Java 8 optional with Mapstruct

旧巷老猫 提交于 2019-12-13 01:28:37

问题


I have these two classes:

public class CustomerEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String firstName;
    private String lastName;
    private String address;
    private int age;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
}

and

public class CustomerDto {
    private Long customerId;
    private String firstName;
    private String lastName;
    private Optional<String> address;
    private int age;
}

The problem is that Mapstruct doesn't recognize the Optional variable "address".

Anyone has an idea how to solve it and let Mapstruct map Optional fields?


回答1:


This is not yet supported out of the box by Mapstruct. There is an open ticket on their Github asking for this functionality: https://github.com/mapstruct/mapstruct/issues/674

One way to solve this has been added in the comments of the same ticket: https://github.com/mapstruct/mapstruct/issues/674#issuecomment-378212135

@Mapping(source = "child", target = "kid", qualifiedByName = "unwrap")
Target map(Source source);

@Named("unwrap")
default <T> T unwrap(Optional<T> optional) {
    return optional.orElse(null);
}

As pointed by @dschulten, if you want to use this workaround while also setting the option nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS, you will need to define a method with the signature boolean hasXXX() for the field XXX of type Optional inside the class which is the mapping source (explanation in the docs).



来源:https://stackoverflow.com/questions/58313368/use-java-8-optional-with-mapstruct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!