Map multiple fields to one with MapStruct

Stelium picture Stelium · Oct 9, 2018 · Viewed 10.5k times · Source

I have these 3 classes in separate files

public class Book {

   @Id
    @GeneratedValue
    private Long id;

    @NonNull
    private String title;

    @NonNull
    private Author author;

}

public class Author {

    @Id
    @GeneratedValue
    private Long id;

    @NonNull
    private String firstName;

    @NonNull
    private String lastName;

}

public class BookDTO {

    private Long id;

    @NonNull
    private String title;

    @NonNull
    private String author;

}

I have the following mapper

@Mapper
public interface BookMapper { 

    BookMapper INSTANCE = Mappers.getMapper(BookMapper.class);

    @Mappings({
            @Mapping(source = "author.lastName", target = "author")
    })
    BookDTO toDTO(Book book);

}

this currently only maps the lastName and works, and I want to map the author string in Book with

author.firstName + " " + author.lastName

how could I do that? I have not been able to find anything in the MapStruct Documentation.

Answer

Filip picture Filip · Oct 9, 2018

MapSruct does not support mapping multiple source properties into a single target property.

You have 2 ways to achieve this:

Using Mapping#expression

@Mapping( target = "author", expression = "java(book.getAuthor().getFirstName() + \" \" + book.getAuthor().getLastName())")

Using @AfterMapping or @BeforeMapping

@Mapper
public interface BookMapper { 

    BookMapper INSTANCE = Mappers.getMapper(BookMapper.class);


    @Mapping(target = "author", ignore = true)
    BookDTO toDTO(Book book);

    @AfterMapping
    default void setBookAuthor(@MappingTarget BookDTO bookDTO, Book book) {
        Author author = book.getAuthor();
        bookDTO.setAuthor(author.getFirstName() + " " + author.getLastName());
    }

}