Spring Data MongoDB映射默认情况下将BigDecimal转换为String。但是,我希望它们在mongodb中转换为Double。这是后者在mongodb(比较查询/聚合查询)中对此字段进行查询所必需的。 我如何重新编译自己的转换器(BigDecimalToDouble / DoubleToBigDecimal)来执行此操作?
答案 0 :(得分:3)
以下是如何添加自己的转换器:
<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>
现在您的转换器看起来像:
@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();
}
}
在添加转换器之前,我得到了:
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
添加转换器后:
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