Explicitly configuring Custom Codec for POJO

Hi,

I’m attempting to store an object in a MongoDB database (using MongoDB 3.12.6) and am getting following error:

org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when encoding using the AutomaticPojoCodec."

I am using the following lines of code currently to create CodeRegistry:

CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));

But for some reason AutomaticPojoCodec generated here does not seem to work to encode/decode POJO.

Could anyone please feedback ?

1 Like

Did you then put it something like below (I also followed the document to connect it)

CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));

try {
	ConnectionString connectiontring = new ConnectionString(
			"your connection");
MongoClientSettings clientSettings = MongoClientSettings.builder()
		 .codecRegistry(pojoCodecRegistry)
		.applicationName("project name")
		.applyToConnectionPoolSettings(builder -> builder.maxWaitTime(20000, TimeUnit.MILLISECONDS))
		.applyConnectionString(connectiontring).retryWrites(false).build();

MongoClient mongoClient = MongoClients.create(clientSettings);

MongoDatabase database = mongoClient.getDatabase("your_database")
 .withCodecRegistry(pojoCodecRegistry);

		return database;

	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

Hi [Pat_Yue]

Thanks for the reply. Unfortunately, this approach again do not work and gives the same error. Following is the error:

org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when encoding using the AutomaticPojoCodec.
Encoding a AadharForm: ‘controller.AadharForm@42917caa’ failed with the following exception:

Failed to encode ‘AadharForm’. Encoding ‘servletWrapper’ errored with: Unable to get value for property ‘servletFor’ in ActionServletWrapper

Regards,
Joe