我是Mapstruct的新手。我有一个包含 LocalDateTime 类型字段的模型对象。 DTO包含 Instant 类型字段。我想将 LocalDateTime 类型字段映射到 Instant 类型字段。我有 TimeZone 传入请求的实例。
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()) )如何使用Mapstruct映射这些字段?
How can I map these fields using with Mapstruct?
推荐答案您有2种选择来实现
第一个选项:
使用新的 @Context < timeZone 属性的1.2.0.Final版本中的/ code>批注,并定义您自己的执行映射的方法。
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将使用提供的方法在即时和 LocalDateTime 。
MapStruct will then use the provided method to perform mapping between Instant and LocalDateTime.
第二个选项:
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
更多推荐
Mapstruct LocalDateTime到即时
发布评论