MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Connessione a MongoDB 3.0 con Java Spring

Dopo molti tentativi e letture, ho trovato un modo per far funzionare MongoDB 3.0 con l'autenticazione.

Questa era una nuova installazione di MongoDB 3.0, nessun aggiornamento coinvolto.

Ho usato queste dipendenze Maven:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.6.2.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.0.0</version>
</dependency>

avere come genitore

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.2.RELEASE</version>
</parent>

Quindi nel mio file di configurazione avevo

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

E infine, ovunque tu abbia accesso al bean MongoTemplate potrai farlo

mongoTemplate.insert(objectToStore, collectionName);