gpt4 book ai didi

java - 如何在 spring-data-mongodb 框架中将 BigDecimal 转换为 Double

转载 作者:可可西里 更新时间:2023-11-01 09:13:40 26 4
gpt4 key购买 nike

Spring Data MongoDB 映射默认将 BigDecimal 转换为 String。但是,我希望它们在 mongodb 中转换为 Double。这是后者在 mongodb 中对该字段进行查询(比较查询/聚合查询)所必需的。我如何注册自己的转换器 (BigDecimalToDouble/DoubleToBigDecimal) 来执行此操作?

最佳答案

以下是您可以添加自己的转换器的方法:

<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

关于java - 如何在 spring-data-mongodb 框架中将 BigDecimal 转换为 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23358778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com