使用MapStruct将多个字段映射到一个字段

时间:2018-10-09 13:15:17

标签: mapstruct

我在单独的文件中有这三个类

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文档中找到任何内容。

1 个答案:

答案 0 :(得分:7)

MapSruct不支持将多个源属性映射到单个目标属性。

您可以通过两种方法实现这一目标:

使用Mapping#expression

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

}