Search code examples
javatomcat7jndiconnection-pooling

Centralize in a single class the lookup of a resource in Tomcat 7 jdni


I'm creating a web app using NetBeans and Tomcat 7 and I wanted to create my first connection pool. I've followed all the steps in the tomcat documentation here: http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html

But in my application I'll have many DAO objects with many different methods each, so I'd like to avoid writing the code for looking up the datasource and getting a connection in each and every method that access to the DB, so I've created a class to centralize this operation and return a connection to the different DAO objects.

You can see the code below, but as I said it's my first time wth this, so I'm not sure... does this make sense for you? is there a better way to do something like that? or it's just better to write this code in each method?

And if this does make sense, could I use the Context or even also the DataSource as static attributes to avoid continuous lookups?

Thanks very much!

My ConnectionPool class:

package dao.mysql;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.tomcat.jdbc.pool.DataSource;


public class ConnectionPool {

    public static Connection getConnection() {
        Connection connection = null;
        try {            
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource)envCtx.lookup("jdbc/EmployeeDB");

            connection = ds.getConnection();

        } catch (SQLException ex) {
            Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
        }
        return connection;
    }
}

Solution

  • You can use JDBC Connection Pool as a singleton bean as described here in this article.