1

I tried to follow the approach mentioned in this page, but could not concat name and surname fields.

Here is what I tried:

@Mapper(componentModel = "spring")
public interface PostDtoMapper {

    Post toEntity(PostDto source);

    @Mapping(ignore = true, source = "user", target = "user")
    @Mapping( target = "userName", source = "user.firstName")
    PostDto toDto(Post destination);

    @AfterMapping
    default void toDto(@MappingTarget PostDto postDto, Post post) {
        User user = post.getUser();
        postDto.setUserName(user.getFirstName() + " " + user.getLastName());
    }
}

But it only gives the firstName value. Any idea?

1 Answers1

0

First of all, remove the following annotation:

@Mapping(target = "userName", source = "user.firstName")

It is no longer needed because you set this field in @AfterMapping

Or even better to replace it with the following:

@Mapping(target = "userName", ignore = true)

Secondly, check if user.getLastName() is not null ;) I have reproduced your example and it is working fine.

Hope it will helps you!

Max Aminov
  • 357
  • 4
  • 8
  • Interesting, but I think the problem is related to `clean install` command. Thanks a lot. –  Feb 26 '23 at 18:25
  • Sure, when you run `install` it generates implementations for your mapstruct annotations, therefore if you did not do this before run, it will fail or use previously generated classes – Max Aminov Feb 26 '23 at 18:28
  • DO you know how to do in Gradle with skipping tests? I am new for Gradle. –  Feb 26 '23 at 18:32
  • 1
    `gradle build -x test` – Max Aminov Feb 26 '23 at 18:35