javaspringspring-bootmapstructjava.time.instant

Set datetime field now in MapStruct?


I have an Instant field in my POJO class and want to set its value now() while creating record. As far as I see, MapStruct let this kind of feature, but I could not set it properly:

mapper:

@Mapper(componentModel = "spring", imports = {Instant.class})
public interface CreatePostRequestMapper {

    // @Mapping(target = "createdAt", defaultExpression ="java(Instant.now())")
    @Mapping(target = "createdAt", defaultValue = "java(Instant.now())")
    Post toEntity(CreatePostRequest source);

    CreatePostRequest toDto(Post destination);
}

And both classes has the same property with the same name:

private Instant createdAt;

Here is the service method:

private final CreatePostRequestMapper createPostRequestMapper;

public PostDetails createPost(@Valid CreatePostRequest request) {
    final Post post = createPostRequestMapper.toEntity(request);

    // code omitted
}

This gives the following error:

"Request processing failed; nested exception is java.time.format.DateTimeParseException: Text 'java(Instant.now())' could not be parsed at index 0] with root cause"

How can solve this?


Solution

  • When you use defaultValue for Instant class, it will generate following code:

    post.setCreatedAt( Instant.parse( "java(Instant.now())" ) );
    

    And, obviously, Instant class cannot parse this string and create an object.

    So, the right way is to use defaultExpression, this will generate following code:

    post.setCreatedAt( Instant.now() );
    

    The difference is noticeable :)

    Hope it will help you.