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.
MapSruct does not support mapping multiple source properties into a single target property.
You have 2 ways to achieve this:
@Mapping( target = "author", expression = "java(book.getAuthor().getFirstName() + \" \" + book.getAuthor().getLastName())")
@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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With