Description
Summary
This is the exact same issue that has been raised in JAVA-5134 for Kotlin driver, but affecting Java record codecs, which when decoding a nullable field when persisted field exists and contains null value (BSONType is NULL), the Java record codec could not handle the scenario correctly and will thrown a BsonInvalidOperationException.
Please provide the version of the driver. If applicable, please provide the MongoDB server version and topology (standalone, replica set, or sharded cluster).
Affected versions of Java driver: 4.11
How to Reproduce
Below test case reproduces the issue, included in https://github.com/mongodb/mongo-java-driver/pull/1223:
// Sample record
|
|
|
import javax.annotation.Nullable; |
|
|
public record TestRecordWithNullableAnnotation (@BsonId ObjectId id, @Nullable String name) { |
}
|
// Sample test
|
@Test
|
public void testRecordWithStoredNulls() { |
var codec = createRecordCodec(TestRecordWithNullableAnnotation.class, Bson.DEFAULT_CODEC_REGISTRY); |
var identifier = new ObjectId(); |
var testRecord = new TestRecordWithNullableAnnotation(identifier, null); |
|
|
var document = new BsonDocument("_id", new BsonObjectId(identifier)) |
.append("name", new BsonNull()); |
|
|
// when |
var decoded = codec.decode(new BsonDocumentReader(document), DecoderContext.builder().build()); |
|
|
// then |
assertEquals(testRecord, decoded);
|
}
|
Additional Background
I have already made a patch to fix this at https://github.com/mongodb/mongo-java-driver/pull/1223, which contains a fix in Java record codec and also a test verifying the patch is working.