Avanst
Avanst

Reputation: 2255

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?

Upvotes: 7

Views: 5132

Answers (4)

user177800
user177800

Reputation:

new InitialContext() is expensive in every application container, it should be a static final and created in a static {} block, effectively making it a Singleton. You should only have to create this reference once and re-use it everywhere you need it.

DataSource should be a static as well. You should have a public static Connection getConnection(); method to retrieve Connection objects, the code should never have to deal with DataSource directly. This works especially well with PooledDataSource implementations.

Upvotes: 4

Tim Funk
Tim Funk

Reputation: 879

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.

Upvotes: 3

limc
limc

Reputation: 40160

You can do something like this too:-

...

Context initContext = new InitialContext();
DataSource dataSource = (DataSource) initContext.lookup("java:comp/env/jdbc/datasource");

...

Upvotes: 2

Amol Katdare
Amol Katdare

Reputation: 6760

Your lookup code looks ok
In your problem context, caching the datasource seems fine as long as you are not caching the actual connection object.

I haven't used this approach in a while though. These days, at a minimum, I use spring to inject the datasource/initialize JdbcTemplate

Upvotes: 1

Related Questions