gpt4 book ai didi

spring - 如何在 Spring 中设置自定义 Mongo 格式化程序?

转载 作者:IT老高 更新时间:2023-10-28 13:30:37 26 4
gpt4 key购买 nike

我已经在这工作了几个小时,但还没有找到任何人让这个工作。我想在 Mongo 中保留一个 BigDecimal 对象,但 Mongo 本身并不支持 BigDecimal。我关注了 Spring 的文档 here但没有运气。

据我所知,Spring 在写入数据库时​​并没有将我的自定义转换器类注入(inject)到 Mongo 中。这是我所做的:

我的 applicationContext-services.xml...

    <!-- Factory bean that creates the Mongo instance -->
<mongo:mongo
host="localhost"
port="1234" />

<mongo:db-factory
dbname="solar"
mongo-ref="mongo"/>

<mongo:mapping-converter>
<mongo:custom-converters>
<mongo:converter>
<bean class="com.mine.BigDecimalReadConverter"/>
</mongo:converter>
<mongo:converter>
<bean class="com.mine..BigDecimalWriteConverter"/>
</mongo:converter>
</mongo:custom-converters>
</mongo:mapping-converter>

<!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

<bean id="mongoDbTest"
class="com.mine.MongoDbTest">
<property name="mongoTemplate">
<ref local="mongoTemplate" />
</property>
</bean>

我得到的错误是:

java.lang.IllegalArgumentException: Multiple constructors with arguments found in class java.math.BigDecimal! Annotate one with @PreferedConstructor explicitly to select it to be used in persistence operations.
at org.springframework.data.mapping.PreferredConstructorDiscoverer.<init>(PreferredConstructorDiscoverer.java:81)

最佳答案

尝试使用它来支持转换器:

<bean id="mappingContext"
class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" lazy-init="true"/>

<bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper" lazy-init="true">
<constructor-arg name="typeKey"><null/></constructor-arg>
</bean>

<bean id="mappingMongoConverter"
class="org.springframework.data.mongodb.core.convert.MappingMongoConverter" lazy-init="true" >
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate" lazy-init="true">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
</bean>

关于spring - 如何在 Spring 中设置自定义 Mongo 格式化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7132992/

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