My problem like this CodecConfigurationException when saving ZonedDateTime to MongoDB with Spring Boot >= 2.0.1.RELEASE
but I'm wrote a custom ZonedDateTime converters:
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"));
}
}
and my test:
@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);
}
if I add a ZDT instance to a first level of a document like this doc.append("a", ZonedDateTime.now())
- document saves fine. But if I place a ZDT instance to a document as a nested field (second level of nesting) I receive an exception:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.time.ZonedDateTime.
What I'm doing wrong?
I solved the alike problem by adding the converters to custom converters configuration:
@Configuration
public class MongoCustomConverterConfig {
@Bean
public MongoCustomConversions mongoCustomConversions(){
List<Converter<?,?>> converters = new ArrayList<>();
converters.add(new ZoneDateTimeWriteConverter());
converters.add(new ZonedDateTimeReadConverter());
return new MongoCustomConversions(converters);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.