The annotation convention uses @BsonProperty("field") value to either look up the field mapping in the ClassModel or creates a new one PropertyModel.
However, special handling for @BsonId fields means that if the _id field property is missing in the ClassModel then it throw an NPE error.
The following Pojo should be able to decode from the DB
I opted against allowing the following model to be able to decode from MongoDB:
public class CreatorConstructorIdSimpleModel { private final SimpleModel simpleModel; private final String stringField; private final long longField; @BsonCreator public CreatorConstructorIdSimpleModel( @BsonId final SimpleModel simpleModel, @BsonProperty("stringField") final String stringField, @BsonProperty("longField") final long longField) { this.id = id; this.stringField = stringField; this.longField = longField; } // equals / hashcode / toString methods
Test case:
CreatorConstructorIdSimpleModel model = new CreatorConstructorIdSimpleModel(getSimpleModel(), "twelve", 13); decodesTo(getPojoCodecProviderBuilder(CreatorConstructorIdSimpleModel.class, SimpleModel.class), "{'_id': " + SIMPLE_MODEL_JSON + ", 'stringField': 'twelve', 'longField': {$numberLong: '13'}}", model);
The reason being supporting the @BsonId in the constructor would make the ClassModel asymmetrical and that is non-obvious. It would encode differently to decoding. So opted for a clearer error message instead. This helps the user to correct the issue with the model and help the PojoCodec decide the right cause of action.
- is related to
-
JAVA-4833 Using @BsonId in a @BsonCreator constructor has confusing behavior
- Closed