How to convert BigDecimal to Double in spring-data

2019-05-07 11:08发布

问题:

Spring Data MongoDB mapping by default converts BigDecimal to String. However, I want them to be converted as Double in mongodb. This is required for latter to make queries on this field in mongodb (comparison queries/aggregation queries). How can I reigster my own converter (BigDecimalToDouble / DoubleToBigDecimal) to do this?

回答1:

Here's how you can add your own converters:

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongoDbFactory"/>
    <constructor-arg ref="mappingConverter"/>
    <property name="writeConcern">
        <util:constant static-field="com.mongodb.WriteConcern.FSYNC_SAFE"/>
    </property>
    <property name="writeResultChecking">
        <util:constant static-field="org.springframework.data.mongodb.core.WriteResultChecking.EXCEPTION"/>
    </property>
</bean>

<mongo:mapping-converter id="mappingConverter">
    <mongo:custom-converters base-package="com.vladmihalcea.**.mongo.converter"/>
</mongo:mapping-converter>

Now your converters would look like:

@Component
public class DoubleToBigDecimalConverter implements Converter<Double, BigDecimal> {

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

@Component
public class BigDecimalToDoubleConverter implements Converter<BigDecimal, Double> {

    @Override
    public Double convert(BigDecimal source) {
        return source.doubleValue();
    }
}

Before adding converter I got:

update test.product query: { _id: 123 } update: { _id: 123, _class: "com.vladmihalcea.mongo.model.Product", name: "Tv", quantity: "10", discount: "12.34", version: 0 } nscanned:0 nupdated:1 upsert:1 keyUpdates:0 locks(micros) w:49328 50ms

After adding converters:

update test.product query: { _id: 123 } update: { _id: 123, _class: "com.vladmihalcea.mongo.model.Product", name: "Tv", quantity: "10", discount: 12.34, version: 0 } nscanned:0 nupdated:1 upsert:1 keyUpdates:0 locks(micros) w:64689 65ms