Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@davutg 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