gpt4 book ai didi

mapstruct - 使用 MapStruct 将多个字段映射为一个

转载 作者:行者123 更新时间:2023-12-03 14:31:09 65 4
gpt4 key购买 nike

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

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

}

这目前只映射 lastName 和作品,我想用 Book 映射作者字符串
author.firstName + " " + author.lastName

我怎么能那样做?我在 MapStruct 文档中找不到任何内容。

最佳答案

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

}

关于mapstruct - 使用 MapStruct 将多个字段映射为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52722015/

65 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com