[JAVA-4838] Support using @BsonId with @BsonCreator Created: 12/Jan/23  Updated: 28/Oct/23  Resolved: 27/Jan/23

Status: Closed
Project: Java Driver
Component/s: POJO
Affects Version/s: None
Fix Version/s: 4.9.0

Type: Improvement Priority: Unknown
Reporter: Ross Lawley Assignee: Ross Lawley
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Documented
Related
is related to JAVA-4833 Using @BsonId in a @BsonCreator const... Closed
Documentation Changes: Needed
Documentation Changes Summary:

We need to mention this change in What's new.


 Description   

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.



 Comments   
Comment by Githook User [ 27/Jan/23 ]

Author:

{'name': 'Ross Lawley', 'email': 'ross.lawley@gmail.com', 'username': 'rozza'}

Message: PojoCodec BsonId error message (#1071)

Help users when using a BsonId in a constructor and there is no
known Id property in the model.

JAVA-4838
Branch: master
https://github.com/mongodb/mongo-java-driver/commit/b0f05c8d24a7f6b160d2196b1aeade41aa5cb51d

Generated at Thu Feb 08 09:03:06 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.