[JAVA-3592] BSON Descriminator does not work after a mongo client is closed Created: 15/Jan/20  Updated: 27/Oct/23  Resolved: 15/Jan/20

Status: Closed
Project: Java Driver
Component/s: Codecs
Affects Version/s: 3.12.0
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Jerry DIMITRIOU Assignee: Ross Lawley
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

BSON Discriminator annotation does not seem to work properly after a mongo client is closed.

I have created a repo replicating the bug which you can find here: https://github.com/jerouris/Mongo-bson-discrimination-bug

 

 



 Comments   
Comment by Ross Lawley [ 15/Jan/20 ]

Thanks jerouris@gmail.com, will look to improve the error messaging and documentation.

Comment by Jerry DIMITRIOU [ 15/Jan/20 ]

Hi Ross,

OK, I got it! This means that @BsonDiscriminator annotations and PojoCodecProvider.builder().automatic(true) does not work well together, because the automatic scanner will register the class lazily on insert.

I've changed the code of the PojoCodecProvider to:

 

PojoCodecProvider
         .builder()
         .register("discriminatorbug")
         .build())

and the classes are now properly registered. I would recommend having that remark somewhere in the docs. There are also others having the same issue, not knowing how easy it is to fix.

 

The issue can be closed.

Comment by Ross Lawley [ 15/Jan/20 ]

Hi jerouris@gmail.com,

Thanks for the ticket and the excellent repro case! The issue here is the use of shortnames for the discriminator for the classes that have not been explicitly registered by the POJO Codec. The automatic POJO codec registry can only handle classes its seen and as you recreate the registry to simulate a restart, then any reference to these short forms have been lost.

In this case you either have to remove the shortnames - so that the full class path is used and they can be loaded by the automatic POJO codec registry, orr explicitly register any classes that use shorten names for their discriminator.

I hope that helps,

Ross

Comment by Ross Lawley [ 15/Jan/20 ]

The error is:

org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when decoding using the AutomaticPojoCodec.
Decoding into a 'TheAbstractClass' failed with the following exception:

Failed to decode 'TheAbstractClass'. Decoding errored with: A class could not be found for the discriminator: 'FirstConcreteClass'.

A custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type.

Generated at Thu Feb 08 08:59:58 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.