Consider this code:
var uuid = UUID.randomUUID() var dbo1 = new BasicDBObject("_id", uuid); var dbo2 = new BasicDBObject("_id", uuid) boolean equal = dbo1.equals(dbo2)
In the 3.x driver equal will be true, but in 4.x it will throw:
Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: The uuidRepresentation has not been specified, so the UUID cannot be encoded. at org.bson.codecs.UuidCodec.encode(UuidCodec.java:72) at org.bson.codecs.UuidCodec.encode(UuidCodec.java:37) at org.bson.codecs.EncoderContext.encodeWithChildContext(EncoderContext.java:91) at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:246) at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:159) at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:67) at com.mongodb.BasicDBObject.toBson(BasicDBObject.java:225) at com.mongodb.BasicDBObject.equals(BasicDBObject.java:215)
This is a breaking change. I think we can get around it though, because in the case of equality we don't really care what uuid representation is used, since we are only using its encoded form to test equality and then throw it away.
Known workarounds:
- Use the org.bson.Document class, which has a more straightforward equals method that does not attempt to encode any values
- Manually convert UUID to BsonBinary, e.g. BsonBinary(UUID.randomUUID(), UuidRepresentation.JAVA_LEGACY)
Both are pretty invasive changes, though.
This issue was originally reported in the Community Forums at https://developer.mongodb.com/community/forums/t/issue-with-uuid-after-upgrading-to-4-2-1-for-java-client/98519.
- related to
-
JAVA-4140 BasicDBObject/Document toString methods throw exceptions when one of the fields is a UUID
- Closed