Posts

Showing posts from June, 2017

Custom converter for Mongodb and Spring Data for BigDecimal type

Recently I found that MongoDB does not support java's java.math.BigDecimal as you can read in the official spring data mongodb documentation As it turns out java.math.BigDecimal will be converted to java.lang.String when saved to the database and parsed back to BigDecimal which in most cases I guess it's alrightHowever as I found out things get broken when trying to perform range queries on this field such as : $gte, $lte you will get inconsistent results since MongoDB sees this as a StringLuckily this can be easily fixed by creating 2 custom converters (one for each side), below is how I've done it :1. Define custom converters by implementing the appropriate interface import org.springframework.core.convert.converter.Converter; import java.math.BigDecimal; public class BigDecimalToDoubleConverter implements Converter<BigDecimal, Double&gt { @Override public Double convert(BigDecimal source) { return source.doubleValue(); } } import org.spr…