Spring Data MongoDB Repository with custom collection name

后端 未结 4 1036
别那么骄傲
别那么骄傲 2021-01-06 01:18

I am using Spring Data for MongoDB and I need to be able to configure collection at runtime.

My repository is defined as:

@Repository
public interfac         


        
4条回答
  •  太阳男子
    2021-01-06 01:26

    Entity Class

    @Document    // remove the parameters from here
    
    
    public class EscalationCase 
    {
    
    }
    

    Configuration class

    public class MongoDBConfiguration {
    
        private final Logger logger = LoggerFactory.getLogger(MongoDBConfiguration.class);
    
        @Value("${sfdc.mongodb.collection}") //taking collection name from properties file 
        private String collectionName;
    
        @Bean
    
        public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoMappingContext context) {
    
            MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory), context);
            converter.setTypeMapper(new DefaultMongoTypeMapper(null));
            MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
            if (!mongoTemplate.collectionExists(collectionName)) {
                mongoTemplate.createCollection(collectionName);  // adding the collection name here
            }
            return mongoTemplate;
    
        }
    }
    

提交回复
热议问题