Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapStruct / Java - Conversion Timestamp to Instant

I have this Mapper, and I want to convert a Entity to a DTO. My Entity contains the variable createdDate who is an Instant and my DTO contains commentedDate who is a Timestamp.

I don't know how it's possible to convert automatically the Instant to Timestamp whit MapStruct.

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

Thanks for your help :)

like image 568
Fizik26 Avatar asked Oct 21 '25 15:10

Fizik26


1 Answers

This question is really similar to Mapstruct LocalDateTime to Instant. The only difference is that this asks for conversion between Timestamp and Instant.

The best way to achieve that is to provide a custom mapping method. For example:

@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);
    }
}

Using this all Instant(s) would be mapped to Timestamp. You can also extract that method into a static util class and then use it via Mapper#uses

like image 180
Filip Avatar answered Oct 23 '25 04:10

Filip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!