How to use Mongo with Spring Data without ObjectId

后端 未结 4 387
小蘑菇
小蘑菇 2021-01-18 10:23

I have an existing mongo database in which ids (_id) are persisted as plain Strings.. This is sample data in Mongo DB:

{
    \"_id\" : \"528bb0e2e4b0442f1479         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 11:06

    A workaround that could work is to create your own converter for ObjectId.

    You can customize the mongo mapper by supplying a @Bean of type MappingMongoConverter

    @Configuration
    public class MongoConfig {
    
        @Bean
        public CustomConversions customConversions() {
            List> converters = new ArrayList>();
            converters.add(new MyObjectIdConverter());
            return new CustomConversions(converters);
        }
    
        @Bean
        public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
            DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
            MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
            try {
                mappingConverter.setCustomConversions(customConversions());
            }
            catch (NoSuchBeanDefinitionException ignore) {}
    
            // Don't save _class to mongo
            mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
    
            return mappingConverter;
        }
    
    }
    

提交回复
热议问题