保存具有 Class 属性的文档时捕获异常 CodecConfigurationException: Can't find a codec for CodecCacheKey{clazz=class java.lang.Class, types=null}
@Document("my_document")
public class MyDocument {
@Id
private String id;
@Field("jPt")
private JobParameter<?> jobParameter;
}
public class JobParameter<T> implements Serializable {
private T value;
private Class<T> type;
private boolean identifying;
}
尝试添加转换器
@Bean
public MongoCustomConversions customConversions(List<Converter<?, ?>> foreignConverters) {
List<Converter<?, ?>> converters = new ArrayList<>(List.of(
JSR310DateConverters.ZonedDateTimeToDateConverter.INSTANCE,
JSR310DateConverters.DateToZonedDateTimeConverter.INSTANCE,
JSR310DateConverters.LongToDurationConverter.INSTANCE,
JSR310DateConverters.DurationToLongConverter.INSTANCE,
**new JobParameterMongoConverter()**
));
converters.addAll(foreignConverters);
MongoCustomConversions mongoCustomConversions = new MongoCustomConversions(converters);
MongoCustomConversions.create(adapter -> adapter.useNativeDriverJavaTimeCodecs()
.registerConverters(converters));
return mongoCustomConversions;
我没有在转换器上使用正确的注释。我使用@ReadingConverter 而不是@WritingConverter。
我发现 Spring Boot 已将 Gradle 配置为拉取旧版本的 MongoDB Kotlin Coroutine 驱动程序 (4.8.2),我不明白为什么。该驱动程序无法正确支持 Kotlin 数据类,因此我需要手动添加对一些 Mongo 项目的额外依赖项,以使一切再次正常运行。愚蠢的春天。
// MongoDB
implementation("org.mongodb:mongodb-driver-core:5.1.3") {
because("Spring pulls 4.8.2 by default which does not support Kotlin. Have I mentioned that Spring is terrible.")
}
implementation("org.mongodb:bson:5.1.3") {
because("Spring pulls 4.8.2 by default which does not support Kotlin.")
}
implementation("org.mongodb:mongodb-driver-reactivestreams:5.1.3") {
because("Spring pulls 4.8.2 by default which does not support Kotlin.")
}
此后,默认编解码器可以正确处理数据类,甚至不需要指定。