Connecting to MongoDB 3.0 with Java Spring

后端 未结 5 1345
一向
一向 2020-12-08 08:51

I am having problems in using Spring to access MongoDB with credentials. While without credentials it works like a charme, using them just fails saying

    F         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 09:54

    After a lot of attempts and reading, I found a way to make MongoDB 3.0 work with authentication.

    This was a new installation of MongoDB 3.0, no upgrade involved.

    I used these maven dependencies:

    
        org.springframework.data
        spring-data-mongodb
        1.6.2.RELEASE
    
    
    
        org.mongodb
        mongo-java-driver
        3.0.0
    
    

    having as parent

    
        org.springframework.boot
        spring-boot-starter-parent
        1.2.2.RELEASE
    
    

    Then in my Configuration file I had

    /**
     * DB connection Factory
     * 
     * @return a ready to use MongoDbFactory
     */
    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
    
        // Set credentials      
        MongoCredential credential = MongoCredential.createCredential(mongoUser, databaseName, mongoPass.toCharArray());
        ServerAddress serverAddress = new ServerAddress(mongoHost, mongoPort);
    
        // Mongo Client
        MongoClient mongoClient = new MongoClient(serverAddress,Arrays.asList(credential)); 
    
        // Mongo DB Factory
        SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(
                mongoClient, databaseName);
    
        return simpleMongoDbFactory;
    }
    
    /**
     * Template ready to use to operate on the database
     * 
     * @return Mongo Template ready to use
     */
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
    

    And finally wherever you have access to the MongoTemplate bean you'll be able to do

    mongoTemplate.insert(objectToStore, collectionName);
    

提交回复
热议问题