有类似的东西:
@Getter @Setter
public static class Entity {
private int hash;
private LocalDateTime createdTime;
}
and
@Getter @Setter
public static class DTO {
private String hash;
private String createdTime;
}
我需要双向映射,所以我应该能够映射实体 -> DTO -> 实体。在此示例中,属性类型恰好是LocalDateTime
但可以是任何需要解析的类型String
左右(只是说我不追求更好的方式来映射LocalDateTime
但一般而言)。
映射时没有问题。我创造TypeMap
, add Converter
并为LocalDateTime
a Provider
还因为它确实注意到有公共默认构造函数。就像是here https://stackoverflow.com/q/39454492/6413377.
如果我的 DTO 中也有LocalDateTime createdTime
(or String createdTime
in my Entity
) then ModelMapper.validate()
会很高兴。但我没有,我需要创建所有转换的东西。
这一切导致ModelMapper.validate()
抱怨:
Unmapped destination properties found in TypeMap[DTO -> Entity]:
org.example.test.modelmapper.validation.TestIt$Entity.setCreatedTime()
我目前用于验证映射的代码LocalDateTime
案例是:
ModelMapper mm = new ModelMapper();
mm.createTypeMap(Entity.class, DTO.class);
mm.createTypeMap(DTO.class, Entity.class);
mm.createTypeMap(String.class, LocalDateTime.class)
.setPropertyProvider(localDateTimeProvider);
mm.addConverter(toStringDate);
mm.validate();
(所以我没有做任何实际的映射,而是验证映射)
with
Provider<LocalDateTime> localDateTimeProvider =
new AbstractProvider<LocalDateTime>() {
@Override
public LocalDateTime get() {
return LocalDateTime.now();
}
};
and
Converter<String, LocalDateTime> toStringDate = new AbstractConverter<>() {
@Override
protected LocalDateTime convert(String source) {
return LocalDateTime.parse(source);
}
};
询问更多详细信息/代码。我会根据需要更新问题