Link to home
Start Free TrialLog in
Avatar of dyma82
dyma82

asked on

Proper use of Datasources

I am working on a J2EE application in WebSphere 5.1
My application uses a datasource to access its database.
This is the method executed every time the app needs to acquire a connection to the databse:

public static Connection getDBConnection(boolean autoCommit) throws NamingException, SQLException
{
      Hashtable parms = new Hashtable();
      parms.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
      InitialContext ctx = new InitialContext(parms);
      DataSource ds = (DataSource)ctx.lookup("java:comp/env/MyDataSource");
      Connection conn = ds.getConnection();
      if (!autoCommit)
      {
            conn.setAutoCommit(false);
      }
      return conn;
}

Question:
Shouldn't it be way more efficient and logical to save the acquired datasource permanently to be used in the future?
Is there any problem with that approach?

I think the following modification of the original code is way more efficient:

public static Connection getDBConnection2(boolean autoCommit) throws NamingException, SQLException
{
      Hashtable parms = null;
      if(savedDataSource == null) //savedDataSource is a private static field in this class
      {
            parms = new Hashtable();
            parms.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
            InitialContext ctx = new InitialContext(parms);
            savedDataSource = (DataSource)ctx.lookup("java:comp/env/MainAppDataSource");
      }
      Connection conn = savedDataSource.getConnection();
      if (!autoCommit)
      {
            conn.setAutoCommit(false);
      }
      return conn;
}

Does somebody sees any problem with the second version, which keeps the datasource reference for the rest of the application's life?
ASKER CERTIFIED SOLUTION
Avatar of boonleng
boonleng
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of damonf
damonf

No reason you shouldn't do it that way.  DataSource is a factory ... all of your lookups return a reference to the same object anyway.  So your way is fine.