Mapstruct LocalDateTime to Instant

跟風遠走 提交于 2020-01-03 20:59:46

问题


I am new in Mapstruct. I have a model object which includes LocalDateTime type field. DTO includes Instant type field. I want to map LocalDateTime type field to Instant type field. I have TimeZone instance of incoming requests.

Manually field setting like that;

set( LocalDateTime.ofInstant(x.getStartDate(), timeZone.toZoneId()) )

How can I map these fields using with Mapstruct?


回答1:


You have 2 options to achieve what you are looking for.

First option:

Use the new @Context annotation from 1.2.0.Final for the timeZone property and define your own method that would perform the mapping. Something like:

public interface MyMapper {

    @Mapping(target = "start", source = "startDate")
    Target map(Source source, @Context TimeZone timeZone);

    default LocalDateTime fromInstant(Instant instant, @Context TimeZone timeZone) {
        return instant == null ? null : LocalDateTime.ofInstant(instant, timeZone.toZoneId());
    }
}

MapStruct will then use the provided method to perform mapping between Instant and LocalDateTime.

The second option:

public interface MyMapper {

    @Mapping(target = "start", expression = "java(LocalDateTime.ofInstant(source.getStartDate(), timezone.toZoneId()))")
    Target map(Source source, TimeZone timeZone);
}

My personal option would be to use the first one



来源:https://stackoverflow.com/questions/47901178/mapstruct-localdatetime-to-instant

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