我是 Mapstruct 的新手。我有一个模型对象,其中包括LocalDateTime
类型字段。 DTO 包括Instant
类型字段。我想要地图LocalDateTime
将字段键入Instant
类型字段。我有TimeZone传入请求的实例。
像这样手动进行字段设置;
set( LocalDateTime.ofInstant(x.getStartDate(), timeZone.toZoneId()) )
如何使用 Mapstruct 映射这些字段?
您有 2 个选择来实现您想要的目标。
第一个选项:
使用新的@Context
1.2.0.Final 中的注释timeZone
属性并定义您自己的执行映射的方法。就像是:
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
and LocalDateTime
.
第二个选项:
public interface MyMapper {
@Mapping(target = "start", expression = "java(LocalDateTime.ofInstant(source.getStartDate(), timezone.toZoneId()))")
Target map(Source source, TimeZone timeZone);
}
我个人的选择是使用第一个
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)