Prevent Spring Data for Mongo to convert ids to ObjectId

旧城冷巷雨未停 提交于 2019-12-06 03:58:36

问题


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

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

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

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

Thanks!

Diego


回答1:


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

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();
            }
        });
    }
}

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>

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.




回答2:


I've faced same problem and my solution was like below:

  @Bean
  public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, CustomConversions conversions) {
    MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), context) {
      @Override
      public void afterPropertiesSet() {
        conversions.registerConvertersIn(conversionService);
      }
    };
    converter.setCustomConversions(conversions);
    return converter;
  }

The idea is to prevent default converters registration.



来源:https://stackoverflow.com/questions/14329175/prevent-spring-data-for-mongo-to-convert-ids-to-objectid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!