本文介绍了防止Mongo的Spring Data将id转换为ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在现有数据库上使用Spring Data for Mongo.先前的应用程序使用纯字符串作为id而不是ObjectId.

I'm using Spring Data for Mongo on an existing database. The previous application used plain strings for ids instead of ObjectId.

我的问题是Spring Data坚持将字符串转换为ObjectId,这会使所有按id进行的查询均失败.

My problem is that Spring Data insists on converting the strings to ObjectId, which makes all queries by id to fail.

例如,当我执行repository.findOne('')时,执行的查询为{ "_id" : { "$oid" : "50cf9f34458cf91108ceb2b4"}},而应为{ "_id" : "50cf9f34458cf91108ceb2b4" }

For example, when I do repository.findOne(''), the query executed is { "_id" : { "$oid" : "50cf9f34458cf91108ceb2b4"}} when it should be { "_id" : "50cf9f34458cf91108ceb2b4" }

有没有一种方法可以避免Spring Data将字符串ID转换为ObjectId?

Is there a way to avoid Spring Data to convert string ids to ObjectId?

谢谢!

迭戈

推荐答案

我终于找到了解决方案.可能不是最好的选择,但可行.

I finally found a solution for this. Probably not the best option, but works.

我所做的是从StringObjectIdQueryMapperObjectId移除了转换器.这样,我创建了以下Mongo转换器:

What I did was remove the converter from String to ObjectId that MongoTemplate uses through QueryMapper. This way, I created the following Mongo converter:

public class CustomMongoConverter extends MappingMongoConverter {
    public CustomMongoConverter(MongoDbFactory mongoDbFactory, MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
        super(mongoDbFactory, mappingContext);
        conversionService.addConverter(new Converter<String, ObjectId>() {
            @Override
            public ObjectId convert(String source) {
                throw new RuntimeException();
            }
        });
    }
}

然后,我将该转换器的实现传递给MongoTemplate:

And then, I passed that implementation of the converter to MongoTemplate:

<bean id="mongoConverter" class="com.abcompany.model.repositories.utils.CustomMongoConverter">
    <constructor-arg ref="mongoDbFactory"/>
    <constructor-arg>
        <bean class="org.springframework.data.mongodb.core.mapping.MongoMappingContext"/>
    </constructor-arg>
</bean>

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

这样,当尝试从String转换为ObjectId时,它会引发异常,但不会这样做.请注意,您可能只需要从conversionService中删除转换器即可.

This way, when trying to convert from String to ObjectId, it throws an exception and it doesn't do it. Please note that you probably can just remove the converter from conversionService.

这篇关于防止Mongo的Spring Data将id转换为ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 07:19