Difference between MongoFactoryBean and SimpleMongoDbFactory

I am creating an MVC MongoDB Spring application and trying to use Service, DAO pattern.

I read Spring -Data-MongoDB refernce here , but I don't understand what the difference is between MongoFactoryBean and SimpleMongoDbFactory.

What would be better, 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?

There would also be a better way to load MongoDB into Spring MVC, so that it is very scalable and customizable, and also provides the ability to connect any other RDBMS (for the same or another function). (Perhaps there are two different DAO modules for different types of databases?)

+6
source share
2 answers

I am surprised that this question still has not been answered. And although this may not be the exact answer you are looking for, here is my occupation. I found that using the second approach, MongoFactoryBean is a better approach.

Just because there are more configuration options. For example, if you want to install Exception Translator, you can do this easily with MongoFactoryBean .

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

In general, move on to the second approach.

+5
source

I believe that in the first option, you can also set the same settings for 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()); } 
+2
source

All Articles