Question

I am setting up a MongoDB Spring MVC application and trying to use Service, DAO pattern.

I read the Spring-Data-MongoDB refernce here, but I am not understanding what is the differnce between MongoFactoryBean and SimpleMongoDbFactory.

What would be a better way, and why, to create a MongoTemplate bean.

@Configuration
public class SpringMongoConfig {
    public @Bean
    MongoDbFactory mongoDbFactory() throws Exception {
       return new SimpleMongoDbFactory(new MongoClient(), "yourdb");
    }

    public @Bean
    MongoTemplate mongoTemplate() throws Exception {
       MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
       return mongoTemplate;
    }
}

OR.

@Bean
public MongoFactoryBean mongo() {
    MongoFactoryBean mongo = new MongoFactoryBean();
    mongo.setHost(env.getProperty("db.host"));
    mongo.setPort(env.getProperty("db.port",Integer.class,27017));
    return mongo;
}

@Bean
public MongoTemplate mongoTemplate() throws Exception{
    return new MongoTemplate(mongo().getObject(),env.getProperty("db.name"));
}

When do i use MongoFactoryBean and when do i use MongoDbFactory? Do they have different use cases?

Also what would be the best way to bootstrap MongoDB into Spring MVC, in such a way that its highly scaleable and configurable, and also provides provision to plug in any other RDBMS( for same or different functionalty). (Two different DAO impls for various DB types perhaps?)

Was it helpful?

Solution

I am surprised this question has still not been answered. And though this might not be the exact answer you are looking for, here is my take on things. I have found that using the second approach, MongoFactoryBean, is the best approach.

Simply because there are more configuration options. For instance, if you want to set an Exception Translator, you can do so easily with MongoFactoryBean.

If I remember correctly, and I may be wrong, the MongoFactoryBean is meant for convenience for MongoDbFactory. Meaning, it adds another layer of abstraction.

All in all, go with the second approach.

OTHER TIPS

I believe that in the first option you can also set the same settings of the second option:

public @Bean MongoDbFactory mongoDbFactory() throws Exception {
    UserCredentials credentials = new UserCredentials(env.getProperty("db.username"), env.getProperty("db.password"));
    return new SimpleMongoDbFactory(new MongoClient(env.getProperty("db.host"), env.getProperty("db.port",Integer.class, 27017)), env.getProperty("db.name"), credentials);
}

public @Bean MongoTemplate mongoTemplate() throws Exception {
    return new MongoTemplate(mongoDbFactory());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top