Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map multiple fields to one with MapStruct

Tags:

mapstruct

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.

like image 325
Stelium Avatar asked Oct 09 '18 13:10

Stelium


1 Answers

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

}
like image 135
Filip Avatar answered Nov 18 '22 14:11

Filip