1

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
bluepix
  • 107
  • 1
  • 11
  • 1
    I think it's a case for [StringCodec](https://github.com/f4b6a3/uuid-creator/blob/master/src/main/java/com/github/f4b6a3/uuid/codec/StringCodec.java) from [uuid-creator](https://github.com/f4b6a3/uuid-creator). Please, read this [wiki page](https://github.com/f4b6a3/uuid-creator/wiki/4.0.-Library-codecs#stringcodec). – fabiolimace Dec 07 '21 at 17:36

1 Answers1

1

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.

bluepix
  • 107
  • 1
  • 11