无法在MapStruct中连接两个字段。

huangapple go评论69阅读模式
英文:

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 无法在MapStruct中连接两个字段。 我已经复制了您的示例,它运行正常。

希望这对您有所帮助!

英文:

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 无法在MapStruct中连接两个字段。 I have reproduced your example and it is working fine.

Hope it will helps you!

huangapple
  • 本文由 发表于 2023年2月26日 21:30:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定