英文:
Cannot concat 2 fields in MapStruct
问题
我尝试遵循这个页面中提到的方法,但无法将名字和姓氏字段连接起来。
这是我尝试过的内容:
@Mapper(componentModel = "spring")
public interface PostDtoMapper {
Post toEntity(PostDto source);
@Mapping(ignore = true, source = "user", target = "user")
@Mapping(target = "userName", source = "user.firstName")
PostDto toDto(Post destination);
@AfterMapping
default void toDto(@MappingTarget PostDto postDto, Post post) {
User user = post.getUser();
postDto.setUserName(user.getFirstName() + " " + user.getLastName());
}
}
但它只给出了firstName
的值。有什么建议吗?
英文:
I tried to follow the approach mentioned in this page, but could not concat name and surname fields.
Here is what I tried:
@Mapper(componentModel = "spring")
public interface PostDtoMapper {
Post toEntity(PostDto source);
@Mapping(ignore = true, source = "user", target = "user")
@Mapping( target = "userName", source = "user.firstName")
PostDto toDto(Post destination);
@AfterMapping
default void toDto(@MappingTarget PostDto postDto, Post post) {
User user = post.getUser();
postDto.setUserName(user.getFirstName() + " " + user.getLastName());
}
}
But it only gives the firstName
value. Any idea?
答案1
得分: 0
首先,删除以下注释:
@Mapping(target = "userName", source = "user.firstName")
不再需要,因为您已在 @AfterMapping 中设置了该字段。
或者,更好的替代方式是将其替换为以下内容:
@Mapping(target = "userName", ignore = true)
其次,检查 user.getLastName() 是否不为 null 我已经复制了您的示例,它运行正常。
希望这对您有所帮助!
英文:
First of all, remove the following annotation:
@Mapping(target = "userName", source = "user.firstName")
It is no longer needed because you set this field in @AfterMapping
Or even better to replace it with the following:
@Mapping(target = "userName", ignore = true)
Secondly, check if user.getLastName() is not null I have reproduced your example and it is working fine.
Hope it will helps you!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论