【发布时间】:2020-04-30 00:34:24
【问题描述】:
我的问题是这样的CodecConfigurationException when saving ZonedDateTime to MongoDB with Spring Boot >= 2.0.1.RELEASE
但我写了一个自定义 ZonedDateTime 转换器:
ZonedDateTimeToDateConverter
@WritingConverter
public class ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {
@Override
public Date convert(ZonedDateTime source) {
if (source == null) {
return null;
}
return Date.from(source.toInstant());
}
}
DateToZonedDateTimeConverter
@ReadingConverter
public class DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {
@Override
public ZonedDateTime convert(Date source) {
if (source == null) {
return null;
}
return ZonedDateTime.ofInstant(source.toInstant(), ZoneId.of("UTC"));
}
}
和我的测试:
@Autowired
ReactiveMongoOperations operations;
@Test
void test() {
ObjectId id = new ObjectId();
Document doc = new Document();
doc.append("_id", id);
// doc.append("a", ZonedDateTime.now()); // works
doc.append("zd1", new Document("f", ZonedDateTime.now())); // not working
operations.insert(doc, "test-collection").block();
Document found = Mono.from(operations.getCollection("test-collection")
.find(new Document("_id", id)).first()).block();
Assertions.assertNotNull(found);
}
如果我将 ZDT 实例添加到像 doc.append("a", ZonedDateTime.now()) 这样的文档的第一级 - 文档保存得很好。但是,如果我将 ZDT 实例作为嵌套字段(第二级嵌套)放置到文档中,则会收到异常:
org.bson.codecs.configuration.CodecConfigurationException:找不到类 java.time.ZonedDateTime 的编解码器。
我做错了什么?
【问题讨论】:
标签: java mongodb spring-data-mongodb