jeremy303
jeremy303

Reputation: 9241

Should my MongoDB DAOs request unique DB objects?

I'm using the standard MongoDB Java driver to roll my own DAOs. I'm aware that all of my DAOs can share the same Mongo instance, but should all of my DAOs accessing the same database share the same DB object or are there good reasons for a new DB object to be requested or each?

Thanks!

Upvotes: 4

Views: 254

Answers (2)

Remon van Vliet
Remon van Vliet

Reputation: 18595

You can use shared instances of the Mongo class, the DB class and the DBCollection class if that proves to be practical for you. Whether or not you want to from a design perspective is up to you. I'd definitely use Mongo instances as singletons since they're relatively heavy weight (have their own thread pool etc.)

Upvotes: 2

Eve Freeman
Eve Freeman

Reputation: 33145

The "good reason" to share the Mongo object is built-in connection pooling. If it's not practical to share your Mongo object instance between DAOs, then that's a good reason (in my opinion), to create new instances. If it is practical, then you should share it.

Remember that you should use .close() when you're done using a Mongo instance, to prevent leaving open connections.

Upvotes: 1

Related Questions