Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-4838

Support using @BsonId with @BsonCreator

    • Type: Icon: Improvement Improvement
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 4.9.0
    • Affects Version/s: None
    • Component/s: POJO
    • None
    • Needed
    • Hide

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

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

      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.

            Assignee:
            ross@mongodb.com Ross Lawley
            Reporter:
            ross@mongodb.com Ross Lawley
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: