Connection to MongoDB using Morphia

304 views
Skip to first unread message

Vaishnavi Manjunath

unread,
Mar 13, 2017, 10:04:45 AM3/13/17
to Morphia
I am developing a Java Restful web application and planning to use MongoDB with Morphia as ODM . As I am new to MongoDB, I needed a few suggestions.

1. The best way to handle db connections is to make use of db connection pool, which mongoClient takes care of. 

        Morphia morphia = new Morphia();   
        ServerAddress addr = new ServerAddress("127.0.0.1", 27017);  
        String databaseName = "test";  
        MongoClient mongoClient = new MongoClient(addr);  
        Datastore datastore = morphia.createDatastore(mongoClient, databaseName); 

 So I need to reuse the above datastore and not create a new instance upon every request as it can waste a lot of resources and affect performance. Should I be implementing the above as singleton class? Can someone help me through this?

2. Also can someone explain as to how I can set up configuration for db connections such as max connections per host, connection timeout in Morphia using MongoClientOptions?

Enrico Morelli

unread,
Mar 14, 2017, 6:35:26 AM3/14/17
to Morphia


On Monday, March 13, 2017 at 3:04:45 PM UTC+1, Vaishnavi Manjunath wrote:
I am developing a Java Restful web application and planning to use MongoDB with Morphia as ODM . As I am new to MongoDB, I needed a few suggestions.

1. The best way to handle db connections is to make use of db connection pool, which mongoClient takes care of. 

        Morphia morphia = new Morphia();   
        ServerAddress addr = new ServerAddress("127.0.0.1", 27017);  
        String databaseName = "test";  
        MongoClient mongoClient = new MongoClient(addr);  
        Datastore datastore = morphia.createDatastore(mongoClient, databaseName); 

 So I need to reuse the above datastore and not create a new instance upon every request as it can waste a lot of resources and affect performance. Should I be implementing the above as singleton class? Can someone help me through this?


Yes, you can implement as Singleton class. I created a morphia plugin for Play Framework. If you want you can look at https://github.com/morellik/play-morphia.

 
2. Also can someone explain as to how I can set up configuration for db connections such as max connections per host, connection timeout in Morphia using MongoClientOptions?

You can do something like that:


MongoClientOptions options = MongoClientOptions.builder()
             
.connectionsPerHost(100)
             
.maxConnectionIdleTime(60000)
             
.build()

an pass options to MongoClient.
Reply all
Reply to author
Forward
0 new messages