[英]How to map LocalDate to Date using Dozer or ModelMapper?
如何正確設置 Dozer 6.4.1 或 ModelMapper 2.2.0 的映射以成功將java.time.LocalDate
字段映射到java.util.Date
字段,反之亦然?
考慮這些類:
public class Foo {
private LocalDate signatureDate;
// getters and setters
}
public class Bar {
private Date signatureDate;
// getters and setters
}
然后調用mapper.map(fooInstance, Bar.class);
不會工作。
我試過創建和注冊自定義轉換器。 使用 Dozer,我創建了擴展DozerConverter<LocalDate, Date>
類LocalDateToDateConverter
並實現了正確的轉換。 然后像這樣注冊它:
mapper = DozerBeanMapperBuilder
.create()
.withCustomConverter(new LocalDateToDateConverter())
.build();
但是在轉換類時使用com.github.dozermapper.core.converters.DateConverter
代替。
另外值得注意的是,我想要一個適用於所有可能需要這種類型轉換的類的通用解決方案,這樣我就不必為每個類制作轉換器。
使用模型映射器,您可以為Bar
和Foo
類配置Date
和LocalDate
之間的轉換器。
轉換器:
private static final Converter<Date, LocalDate> DATE_TO_LOCAL_DATE_CONVERTER = mappingContext -> {
Date source = mappingContext.getSource();
return source.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
};
private static final Converter<LocalDate, Date> LOCAL_DATE_TO_DATE_CONVERTER = mappingContext -> {
LocalDate source = mappingContext.getSource();
return Date.from(source.atStartOfDay(ZoneId.systemDefault()).toInstant());
};
映射器配置:
ModelMapper mapper = new ModelMapper();
TypeMap<Bar, Foo> barToFooMapping = mapper.createTypeMap(Bar.class, Foo.class);
barToFooMapping.addMappings(mapping -> mapping.using(DATE_TO_LOCAL_DATE_CONVERTER).map(Bar::getSignatureDate, Foo::setSignatureDate));
TypeMap<Foo, Bar> fooToBarMapping = mapper.createTypeMap(Foo.class, Bar.class);
fooToBarMapping.addMappings(mapping -> mapping.using(LOCAL_DATE_TO_DATE_CONVERTER).map(Foo::getSignatureDate, Bar::setSignatureDate));
請注意時區,同時轉換Date
到LocalDate
和LocalDate
到Date
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.