Monday, April 1, 2024

java: spring boot/spring/mongodb: org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class



>PROBLEM


Attempt to save an instance on MongoDB database fails returning:

  org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class ...

  

  or for this example:

  org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.drillback.ws5.model.mongodb.MongoTest.


- other possible error messages:

custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type.] with root cause 
org.bson.BsonInvalidOperationException: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is DOCUMENT.


or yet:

Failed to decode 'MongoInfo'. Decoding 'references' errored with: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is DOCUMENT.
A custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type.] with root cause
org.bson.BsonInvalidOperationException: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is DOCUMENT.


>SOLUTION


Follow the example below, check:

1. The java class has the @Document annotaion.

2. Just one constructor must have @BsonCreator annotation, with all fields.


>Java class example

@Document

//@Document(collection = "test")

public class MongoTest {


// @Id, or @BsonId

@BsonId

@BsonProperty("_id") public BsonObjectId id = null;

@BsonProperty("title") public String title = "";

@BsonProperty("regdate") public Date regdate = new Date();


@BsonCreator

public MongoTest(

@BsonProperty("_id") BsonObjectId id,

@BsonProperty("title") String title,

@BsonProperty("regdate") Date regdate

) {

this.id = id;

this.title = title;

this.regdate = regdate;

}



>ENV

Spring Boot (spring)

MongoDB

Java 17




No comments:

Post a Comment

eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...