[英]MapStruct / Java - Conversion Timestamp to Instant
我有這個Mapper,我想將一個實體轉換為DTO。 我的實體包含一個變量InstantDate,它是一個Instant,而我的DTO包含commentedDate,它是一個時間戳。
我不知道如何將Instant即時轉換為MapStruct。
public interface BlogMapper {
@Mappings({
@Mapping(target = "userId", source = "user.id"),
@Mapping(target = "commentedDate", source = "createdDate")
})
BlogDto entityToDto(final Comment entity);
}
謝謝你的幫助 :)
這個問題確實類似於Mapstruct LocalDateTime to Instant 。 唯一的區別是,這要求在Timestamp
和Instant
之間進行轉換。
實現此目標的最佳方法是提供自定義映射方法。 例如:
@Mapper
public interface BlogMapper {
@Mapping(target = "userId", source = "user.id"),
@Mapping(target = "commentedDate", source = "createdDate")
BlogDto entityToDto(final Comment entity);
default Timestamp map(Instant instant) {
return instant == null ? null : Timestamp.from(instant);
}
}
使用所有這些Instant
將被映射到Timestamp
。 您還可以將該方法提取到靜態util類中,然后通過Mapper#uses
使用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.