Search code examples
javatomcatjdbcdatasource

Adavantage of using connection from Data Source over JDBC Driver Manager


Question is basically identify the best practices on data access layer.

I want to choose in between using a data source or traditional driver manager to load the the connection on web applications. I know very clearly following advantages

  1. Flexibility of configuration
  2. In built connection pooling mechanism

But if I can sacrifice advantage of flexibility with configuration and have own connection pooling mechanism, Do I get any other benefit out of data source. In other way around what are limitations or issues I would face while having application managed jdbc driver connection than container managed.

I know the question is so stupid that I should be knowing the advantage of somebody takes care of handling connection than my application. But this is rare scenario where I can't use datasource in web application. I would be looking following things

  1. How better I can design own connection pool my self?
  2. Is there any thing else I should take care when I access connection through DriverManager API

Solution

  • Note that is is very possible to programmatically create a DataSource (backed by a connection pool) dynamically based on user input.

    Using Apache Commons-dbcp:

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(DATABASE_DRIVER_CLASS);
    ds.setUsername(DATABASE_USERNAME);
    ds.setPassword(DATABASE_PASSWORD);
    ds.setUrl(DATABASE_URL);
    ds.setInitialSize(1);
    ds.setMaxActive(50);
    ds.setDefaultAutoCommit(false);
    

    So I think the question is not really between a DataSource and no-DataSource, but rather between a container managed DataSource and an application managed DataSource.

    Container managed DataSources are easier to manage by server-admin types. They can be tuned through the app server web UI, etcApplication managed DataSources do not have this advantage.