MapStruct / Java - 将时间戳转换为即时

MapStruct / Java - Conversion Timestamp to Instant

我有这个 Mapper,我想将实体转换为 DTO。 我的实体包含变量 createdDate,它是一个 Instant,我的 DTO 包含 commentedDate,它是一个时间戳。

我不知道如何将 Instant 自动转换为 Timestamp whit MapStruct。

public interface BlogMapper {
    @Mappings({
            @Mapping(target = "userId", source = "user.id"),
            @Mapping(target = "commentedDate", source = "createdDate")
    })
    BlogDto entityToDto(final Comment entity);
}

感谢您的帮助:)

这道题和真的很像。唯一的区别是这要求在 TimestampInstant 之间进行转换。

实现这一目标的最佳方法是提供自定义映射方法。例如:

@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(s) 将映射到 Timestamp。您还可以将该方法提取到静态 util class 中,然后通过 Mapper#uses

使用它