我正试图将源对象中的属性设置为null
,然后映射到目标对象,而该目标对象的该属性已被设置为另一个对象。
期望的结果是在映射后,目标对象的属性将为null
。但实际上,该属性被设置为一个对象,并且其所有属性都被设置为null
。
以下是一个例子:
public class ModelMapperTest {
public static void main(String[] args) {
ModelMapper modelMapper = new ModelMapper();
User user = new User();
user.setStatus(null);
StatusDto statusDto = new StatusDto();
statusDto.setId(1);
statusDto.setName("Active");
UserDto userDto = new UserDto();
userDto.setStatus(statusDto);
// user.status=null, userDto.status=StatusDto(id=1, name="Active")
modelMapper.map(user, userDto);
System.out.println("user = " + user);
System.out.println("userDto = " + userDto);
}
@Getter
@Setter
@ToString
public static class User {
private Status status;
}
@Getter
@Setter
@ToString
public static class Status {
private Integer id;
private String name;
}
@Getter
@Setter
@ToString
public static class UserDto {
private StatusDto status;
}
@Getter
@Setter
@ToString
public static class StatusDto {
private Integer id;
private String name;
}
}
输出:
user = ModelMapperTest.User(status=null) userDto = ModelMapperTest.UserDto(status=ModelMapperTest.StatusDto(id=null, name=null))
是否可以通过配置model mapper将UserDto.status
设置为null?
ModelMapper
库存在问题。我们决定改用MapStruct
。 - Tuom