Mapstruct LocalDateTime到即时

编程入门 行业动态 更新时间:2024-10-10 15:18:10
本文介绍了Mapstruct LocalDateTime到即时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是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到即时

本文发布于:2023-10-29 00:51:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538220.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Mapstruct   LocalDateTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!