Search code examples
javamongodbuuidcodecbson

UUID represented as Bson String


I think I really have a simple use case but I'm struggling hard to make it work with MongoDB.

I have a POJO which looks like

public class Item {
  @BsonRepresentation(value = BsonType.STRING)
  private UUID id;
  private String version;
  // more..

  // getter/setters
}

You see the POJO has the id specified as UUID. But the Bson representation is a string.

I tried to write my custom codec only for the UUID class but this does not really work. The registry looks like

CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
    MongoClientSettings.getDefaultCodecRegistry(),
    fromProviders(PojoCodecProvider.builder().automatic(true).build()),
    CodecRegistries.fromCodecs(
            new UuidCodec()
    )
)

I would like to write a codec only for the UUID case not for the whole Item class. But as I think I really go into the wrong direction I need any help. How should this be implemented?


Solution

  • Thanks to the input from @fabiolimace I implemented a simple PropertyCodecProvider which returns for the UUID type the codec below

    public class UuidCodec implements Codec<UUID> {
     @Override
     public void encode(BsonWriter writer, UUID value, EncoderContext encoderContext) {
        if (value != null) {
            writer.writeString(value.toString());
        }
     }
    
     @Override
     public UUID decode(BsonReader reader, DecoderContext decoderContext) {
        String uuidString = reader.readString();
        if (uuidString == null || uuidString.isEmpty()) {
            return null;
        }
    
        return UUID.fromString(uuidString);
     }
    
     @Override
     public Class<UUID> getEncoderClass() {
        return UUID.class;
     }
    }
    

    Hope this helps others with a similar challenge.