Created
November 15, 2017 15:37
-
-
Save squarepegsys/9a97f7c70337e7c5e006a436acd8a729 to your computer and use it in GitHub Desktop.
How to get BigDecimal to behave in MongoDb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BigDecimalTransformer implements Transformer{ | |
@Override | |
Object transform(Object objectToTransform) { | |
BigDecimal value = (BigDecimal) objectToTransform; | |
//Again, you may not want a double. | |
return value.doubleValue(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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