3

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 :)

Fizik26
  • 753
  • 2
  • 10
  • 25

1 Answers1

7

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

Filip
  • 19,269
  • 7
  • 51
  • 60