Skip to content

Instantly share code, notes, and snippets.

@squarepegsys
Created November 15, 2017 15:37
Show Gist options
  • Save squarepegsys/9a97f7c70337e7c5e006a436acd8a729 to your computer and use it in GitHub Desktop.
Save squarepegsys/9a97f7c70337e7c5e006a436acd8a729 to your computer and use it in GitHub Desktop.
How to get BigDecimal to behave in MongoDb
public class BigDecimalCodec implements Codec<BigDecimal> {
// Note that you may not want it to be double -- choose your own type.
@Override
public void encode(final BsonWriter writer, final BigDecimal value, final EncoderContext encoderContext) {
writer.writeDouble(value);
}
@Override
public BigDecimal decode(final BsonReader reader, final DecoderContext decoderContext) {
return reader.readDouble();
}
@Override
public Class<BigDecimal> getEncoderClass() {
return BigDecimal.class;
}
class BigDecimalCodecProvider implements CodecProvider{
@Override
def <T> Codec<T> get(Class<T> aClass, CodecRegistry codecRegistry) {
if (aClass==BigDecimal.class) {
return new BigDecimalCodec() as Codec<T>
}
return null
}
}
class BigDecimalTransformer implements Transformer{
@Override
Object transform(Object objectToTransform) {
BigDecimal value = (BigDecimal) objectToTransform;
//Again, you may not want a double.
return value.doubleValue();
}
}
// when you are configuring your Mongo options.
// And, yes, you need both the Codec and the Transformer
BSON.addEncodingHook(BigDecimal.class, new BigDecimalTransformer());
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
CodecRegistries.fromProviders(new BigDecimalCodecProvider()),
MongoClient.getDefaultCodecRegistry()
);
MongoClientOptions.Builder builder = MongoClientOptions.builder()
.codecRegistry(codecRegistry);
[....]
return builder.build();
@davutg
Copy link

davutg commented Sep 20, 2018

I use Java 8 and I couldn't see an implicit conversion between double and Bigdecimal and I just fancied to use our hero "String" type

public class BigDecimalCodec implements Codec<BigDecimal> {
    @Override
    public void encode(final BsonWriter writer, final BigDecimal value, final EncoderContext encoderContext) {
        writer.writeString(value+"");
    }
    
    @Override
    public BigDecimal decode(final BsonReader reader, final DecoderContext ecoderContext) {
        return new BigDecimal(Double.parseDouble(reader.readString()));
    }

    @Override
    public Class<BigDecimal> getEncoderClass() {
        return BigDecimal.class;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment