[英]How to configurate mapstruct to ignore map object when all field are null
[英]Mapstruct: Returning null when trying to map a field inside an embedded object
我们被分配使用 Mapstruct 在 Spring 中重新创建 Twitter API 的简单版本。
我们返回一个List<UserDto>
,它应该从嵌入式 object 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
的嵌入式 object ,其中用户的username
和password
以字符串格式存储(我知道这很愚蠢,这只是一个作业)。
@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
,重命名了变量。 我没主意了。 任何帮助,将不胜感激。
目前不支持您尝试在集合映射方法上使用@Mapping
的方式。 您需要声明从User
到UserDto
的显式映射,并在其上应用注释:
@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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.