我在单独的文件中有这三个类
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;
}
我有以下映射器
@Mapper
public interface BookMapper {
BookMapper INSTANCE = Mappers.getMapper(BookMapper.class);
@Mappings({
@Mapping(source = "author.lastName", target = "author")
})
BookDTO toDTO(Book book);
}
这目前仅映射姓氏并且可以使用,我想使用
映射Book中的作者字符串。author.firstName + " " author.lastName
我该怎么做?我无法在MapStruct文档中找到任何内容。
答案 0 :(得分:7)
MapSruct不支持将多个源属性映射到单个目标属性。
您可以通过两种方法实现这一目标:
@Mapping( target = "author", expression = "java(book.getAuthor().getFirstName() + \" \" + book.getAuthor().getLastName())")
@AfterMapping
或@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());
}
}