Spring Data MongoDB BigDecimal support

那年仲夏 提交于 2019-12-19 07:27:09

问题


guys I have a doubt related to BigDecimal value support by Spring Data MongoDB, could someone help me with some news about it, if there will be support for this type, or if anyone knows a workaround to supply my needs. That's the deal: I'm working on a project where we use MongoDB as a DB and Spring as framework, we would like to save the fields where we are supposed to get money values in the database as BigDecimal, I've read that mongo only accepts double as a float number, but I don't think this type is going to be useful. Could you guys give me some light about it?


回答1:


Spring Data MongoDB converts BigDecimal values to String on write and back to when reading. Please have a look at the data mapping and type conversion section of the reference manual.




回答2:


You can change the converter of BigDecimal do Decimal128 which is the java representation of NumberDecimal since mongo 3.4:

@Bean
public MongoCustomConversions mongoCustomConversions() {
    return new MongoCustomConversions(Arrays.asList(

        new Converter<BigDecimal, Decimal128>() {

            @Override
            public Decimal128 convert(@NonNull BigDecimal source) {
                return new Decimal128(source);
            }
        },

        new Converter<Decimal128, BigDecimal>() {

            @Override
            public BigDecimal convert(@NonNull Decimal128 source) {
                return source.bigDecimalValue();
            }

        }


    ));

}

Actually since Spring Data 2.0.7.RELEASE the above changes to following:

@Bean
public MongoCustomConversions mongoCustomConversions() {
    return new MongoCustomConversions(Arrays.asList(
        new BigDecimalDecimal128Converter(),
        new Decimal128BigDecimalConverter()
    ));

}

@WritingConverter
private static class BigDecimalDecimal128Converter implements Converter<BigDecimal, Decimal128> {

    @Override
    public Decimal128 convert(@NonNull BigDecimal source) {
        return new Decimal128(source);
    }
}

@ReadingConverter
private static class Decimal128BigDecimalConverter implements Converter<Decimal128, BigDecimal> {

    @Override
    public BigDecimal convert(@NonNull Decimal128 source) {
        return source.bigDecimalValue();
    }

}


来源:https://stackoverflow.com/questions/37950296/spring-data-mongodb-bigdecimal-support

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!