我是 Mapstruct 新手。我有一个模型对象,其中包含 LocalDateTime
类型字段。 DTO 包含 Instant
类型字段。我想将 LocalDateTime
类型字段映射到 Instant
类型字段。我有传入请求的 TimeZone 实例。
像这样手动设置字段;
set( LocalDateTime.ofInstant(x.getStartDate(), timeZone.toZoneId()) )
如何使用 Mapstruct 映射这些字段?
最佳答案
您有 2 个选择来实现您想要的目标。
第一个选项:
对 timeZone
属性使用 1.2.0.Final 中新的 @Context
注释,并定义您自己的执行映射的方法。像这样的东西:
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 将使用提供的方法来执行 Instant
和 LocalDateTime
之间的映射。
第二个选项:
public interface MyMapper {
@Mapping(target = "start", expression = "java(LocalDateTime.ofInstant(source.getStartDate(), timezone.toZoneId()))")
Target map(Source source, TimeZone timeZone);
}
我个人的选择是使用第一个
关于java-time - Mapstruct LocalDateTime 到 Instant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47901178/