Michel Feinstein
Michel Feinstein

Reputation: 14306

How to deal with connection pooling and DAOs?

I am learning about JDBC connection pooling and it sounds relatively easy to get a DataSource instance using JNDI:

DataSource ds = (DataSource)ctx.lookup("jdbc/myDB");

All the tutorials I found show this code in one object only, but my question is how to use a DataSource when I have several DAO objects needing to fetch data from a DB.

  1. Is it ok to use the code above for connection pooling on every new DAO object's constructor? I think the same DataSource will be returned every time, much like a Dictionary Singleton would do, holding a single DataSource and returning it, or am I wrong and will it return a different DataSource every time and use different pools, defeating my purpose?

  2. Should I hold that DataSource in a Singleton and only run the JNDI search once or is the search overhead neglectable and this is a silly optimization?

Upvotes: 0

Views: 193

Answers (1)

Andy Guibert
Andy Guibert

Reputation: 42966

  1. Is it ok to use the code above for connection pooling on every new DAO object's constructor? I think the same DataSource will be returned every time, much like a Dictionary Singleton would do, holding a single DataSource and returning it, or am I wrong and will it return a different DataSource every time and use different pools, defeating my purpose?

The same DataSource object ought to be returned each time. If it's not literally the same object, then it ought to at least share the same underlying connection pool.

  1. Should I hold that DataSource in a Singleton and only run the JNDI search once or is the search overhead neglectable and this is a silly optimization?

The search overhead of JNDI is negligible compared to performing operations on a remote database, so it's not necessary to cache the DataSource object.

Upvotes: 1

Related Questions