Search code examples
javatomcatdatasourcejndi

Proper way to call JNDI datasource within Tomcat


I am using a Java web application on a Tomcat server and would like to know what is the "best practice" in terms of accessing a database connection from within Tomcat's JNDI?

Currently this is basically what I am doing each time I need to access the database:

Context envContext = null;
DataSource dataSource = null;
try {
    envContext  = (Context)ctx.lookup("java:/comp/env");
    dataSource = (DataSource)envContext.lookup("jdbc/datasource");
    return dataSource.getConnection();
} catch (Exception e){
    e.printStackTrace();
    return null;
}finally {
    if(envContext != null){
        try{
           envContext.close();
        } catch (NamingException e){
            e.printStackTrace();
        }
    }
}

However, is this the proper way to look up a connection from JNDI each time I want to access the database? Should I hold a reference to the Context or the Datasource instead?


Solution

  • The jndi lookups are essentially Map lookups so their overhead is minimal. But it is preferable to get the DataSource once and "cache" that. So if anything - writing a method to return the DataSource is ideal so as not to bind too much code to J2EE internals and make code easier to test.