Skip to content

Commit 8b06045

Browse files
christophstroblmp911de
authored andcommitted
Fix DocumentToStringConverter UUID representation when calling toJson.
This commit makes sure to use an Encoder having UuidRepresentation set when calling org.bson.Document#toJson, preventing CodecConfigurationException from being raised. Future versions will make sure the UUID string representation matches the Java default one. Closes #3546. Original pull request: #3551.
1 parent 2bf60ac commit 8b06045

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoConverters.java

+10-2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232

3333
import org.bson.BsonTimestamp;
3434
import org.bson.Document;
35+
import org.bson.UuidRepresentation;
36+
import org.bson.codecs.Codec;
37+
import org.bson.internal.CodecRegistryHelper;
3538
import org.bson.types.Binary;
3639
import org.bson.types.Code;
3740
import org.bson.types.Decimal128;
@@ -45,11 +48,12 @@
4548
import org.springframework.data.convert.WritingConverter;
4649
import org.springframework.data.mongodb.core.query.Term;
4750
import org.springframework.data.mongodb.core.script.NamedMongoScript;
48-
import org.springframework.lang.Nullable;
4951
import org.springframework.util.Assert;
5052
import org.springframework.util.NumberUtils;
5153
import org.springframework.util.StringUtils;
5254

55+
import com.mongodb.MongoClientSettings;
56+
5357
/**
5458
* Wrapper class to contain useful converters for the usage with Mongo.
5559
*
@@ -236,9 +240,13 @@ enum DocumentToStringConverter implements Converter<Document, String> {
236240

237241
INSTANCE;
238242

243+
private final Codec<Document> codec = CodecRegistryHelper
244+
.createRegistry(MongoClientSettings.getDefaultCodecRegistry(), UuidRepresentation.JAVA_LEGACY)
245+
.get(Document.class);
246+
239247
@Override
240248
public String convert(Document source) {
241-
return source.toJson();
249+
return source.toJson(codec);
242250
}
243251
}
244252

spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/MappingMongoConverterUnitTests.java

+9
Original file line numberDiff line numberDiff line change
@@ -2181,6 +2181,15 @@ public void readAndConvertDBRefNestedByMapCorrectly() {
21812181
assertThat(((LinkedHashMap) result.get("cluster")).get("_id")).isEqualTo(100L);
21822182
}
21832183

2184+
@Test // GH-3546
2185+
void readFlattensNestedDocumentToStringIfNecessary() {
2186+
2187+
org.bson.Document source = new org.bson.Document("street", new org.bson.Document("json", "string").append("_id", UUID.randomUUID()));
2188+
2189+
Address target = converter.read(Address.class, source);
2190+
assertThat(target.street).isNotNull();
2191+
}
2192+
21842193
@Test // DATAMONGO-1902
21852194
void writeFlattensEmbeddedType() {
21862195

0 commit comments

Comments
 (0)