Singleton and data source

I am developing a web application with Java and need a database connection. It is very important to manage resources well . The application will reside in the Tomcat 6 servlet container, and I implemented BoneCP for connection management (I cannot use Spring).

I read that finding a JNDI for a data source is very expensive , and I think that we will create a singleton of the DataSource object to get the JNDI resource only once and return the same DataSource for future communications.

Question: Is it a good idea to create a DataSource only once and get connections to the same DataSource? I do not want to receive the same connection, only the same DataSource.

Thanks;)

+4
source share
2 answers

Use a federated data source, such as the one described here:

http://www.javaranch.com/journal/200601/JDBCConnectionPooling.html

+3
source

Yes, as Renjit suggested, you only need to create a DataSource once. Yesterday I ran into this problem. Each time in my "getConnection" method, I noticed that I did not create a new InitialContext and DataSource. I revised my Connection Manager class to have a static block of code that only creates a DataSource when the class loads for the first time (after reading the BalusC response into the correct use of the JDBC connection pool (Glassfish) )

I thought about using the old-school ServiceLocator template (see Pascal's answer in the link above), but I felt this overwhelmed my needs.

Another possibility is that you can also use @Resource annotation with injection in DataSources, but it does not work with Tomcat 7 .

+3
source

All Articles