Capacytron
Capacytron

Reputation: 3739

spring-boot 2.3.6, how to set UUID representation for mongo?

I'm trying to upgrade to spring-boot 2.3.6. I'm using spring-data MongoRepositories, no difrect calls to MongoClient or MongoClient.

Getting exception:

Caused by: 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 org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:198)
    at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:212)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:154)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)

Tried to customize

@Bean
    public MongoClientSettingsBuilderCustomizer mongoDBDefaultSettings() {
        return builder -> {
            builder.uuidRepresentation(UuidRepresentation.JAVA_LEGACY);
        };
    }

doesn't help, same exception.

What is the right way to customize UUID codec in spring-boot 2.3.6?

Thank you.

Upvotes: 1

Views: 10246

Answers (3)

Atul
Atul

Reputation: 3357

For MongoDB version 4.3 or later, this is the fix which works for me.

MongoClientSettings settings = MongoClientSettings.builder()
     .uuidRepresentation(UuidRepresentation.STANDARD)
     .build();

Upvotes: 3

awgtek
awgtek

Reputation: 1829

This can happen when you have a plain MongoClient bean defined, e.g.:

@Bean
public MongoClient mongoClient() {
    return MongoClients.create(MongoClientSettings.builder().build());
}

You use the MongoClientSettingsBuilderCustomizer to customize the auto-configured MongoClient. (Note, for later versions of Spring Boot, no customization is needed if the auto-configured MongoClient is used, because by default, as of Spring Boot 2.4.2, MongoProperties sets the UUID representation to JAVA_LEGACY.)

Per the doc:

The auto-configured MongoClient is created using MongoClientSettings. To fine-tune its configuration, declare one or more MongoClientSettingsBuilderCustomizer beans. Each will be called in order with the MongoClientSettings.Builder that is used to build the MongoClientSettings.

If you need to have a custom MongoClient, you can set the UUID representation explicitly, e.g.:

@Bean
public MongoClient mongoClient() {
    return MongoClients.create(MongoClientSettings.builder()
               .uuidRepresentation(UuidRepresentation.JAVA_LEGACY)
               .build());
}

Upvotes: 5

danieldestro
danieldestro

Reputation: 379

On Spring Boot application.properties simply inform:

spring.data.mongodb.uuid-representation=standard

Upvotes: 8

Related Questions