【问题标题】:Mapstruct: Returning null when trying to map a field inside an embedded objectMapstruct:尝试映射嵌入对象内的字段时返回null
【发布时间】:2021-06-15 07:05:16
【问题描述】:

我们被分配到使用 Mapstruct 在 Spring 中重新创建一个简单版本的 Twitter API。

我们正在返回一个 List<UserDto>,它应该从嵌入对象 Credentials 返回字段 username

我们将其映射如下:

@Mapper(componentModel = "spring", uses = {ProfileMapper.class, CredentialMapper.class})
public interface UserMapper {

    User dtoToEntity(CreateUserDto createUserDto);

    @Mapping(target = "username", source = "credentials.username")
    List<UserDto> entitiesToDtos(List<User> users);

}

我们的UserDto 是这样指定的:

@NoArgsConstructor
@Data
public class UserDto {

    private ProfileDto profile;
    private Timestamp joined;
    private String username;

}

我们的User 实体有一个名为credentials 的嵌入对象,其中用户的usernamepassword 以字符串格式存储(我知道这很愚蠢,这只是一个赋值)。

@NoArgsConstructor
@Entity
@Data
@Table(name="users")
public class User {

    @Id
    @GeneratedValue
    private Long id;

    @CreationTimestamp
    private Timestamp joined;

    private boolean deleted;

    @Embedded
    private Credential credentials;

    @Embedded
    private Profile profile;

长话短说,当我们 GET 所有用户时,我们应该会收到这个(这些是假姓名和数字):

{
    "profile": {
        "firstName": "Chanda",
        "lastName": "Hackett",
        "email": "chandahackett@gmail.com",
        "phone": "313-574-1401"
    },
    "joined": "2021-03-17T21:15:35.289+00:00",
    "username": "chandahackett"
}

但相反,我们收到了用户名的 null 值:

{
    "profile": {
        "firstName": "Chanda",
        "lastName": "Hackett",
        "email": "chandahackett@gmail.com",
        "phone": "313-574-1401"
    },
    "joined": "2021-03-17T21:15:35.289+00:00",
    "username": null
}

我知道凭据中的值 username 存在,因为它存在于它存储的表中:

而且它是可访问的,因为其他调用 user.getCredentials().getUsername() 的方法会返回正确的用户名。

我几乎尝试了所有方法。我已经运行mvn clean install,重命名了变量。我没主意了。任何帮助将不胜感激。

【问题讨论】:

    标签: java postgresql spring-boot jpa mapstruct


    【解决方案1】:

    目前不支持您尝试在集合映射方法上使用 @Mapping 的方式。您需要声明一个从UserUserDto 的显式映射,并在其上应用注解:

    @Mapper(componentModel = "spring", uses = {ProfileMapper.class, CredentialMapper.class})
    public interface UserMapper {
        User dtoToEntity(CreateUserDto createUserDto);
        @Mapping(target = "username", source = "credentials.username")
        UserDto entityToDto(User user);
        List<UserDto> entitiesToDtos(List<User> users);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多