Fiz*_*k26 2 java spring mapstruct
我有这个映射器,我想将实体转换为 DTO。我的实体包含变量 createdDate ,他是 Instant ,我的 DTO 包含 commentedDate ,他是时间戳。
我不知道如何通过 MapStruct 将 Instant 自动转换为 Timestamp。
public interface BlogMapper {
@Mappings({
@Mapping(target = "userId", source = "user.id"),
@Mapping(target = "commentedDate", source = "createdDate")
})
BlogDto entityToDto(final Comment entity);
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助 :)
这个问题与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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用这个 all Instant(s) 将被映射到Timestamp. 您还可以将该方法提取到静态 util 类中,然后通过Mapper#uses
| 归档时间: |
|
| 查看次数: |
3985 次 |
| 最近记录: |