我是新来的马普斯特。我有一个模型对象,其中包括LocalDateTime类型字段。DTO包括Instant类型字段。我想将LocalDateTime类型字段映射到Instant类型字段。我有传入请求的TimeZone实例。
手动设置这样的字段;
set( LocalDateTime.ofInstant(x.getStartDate(), timeZone.toZoneId()) )如何使用Mapstruct映射这些字段?
发布于 2017-12-22 22:43:00
你有两个选择来实现你想要的目标。
第一种选择:
对@Context属性使用1.2.0中的新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和LocalDateTime之间的映射。
第二种选择:
public interface MyMapper {
@Mapping(target = "start", expression = "java(LocalDateTime.ofInstant(source.getStartDate(), timezone.toZoneId()))")
Target map(Source source, TimeZone timeZone);
}我个人的选择是使用第一个
https://stackoverflow.com/questions/47901178
复制相似问题