Thursday, January 22, 2009

Configuring JDBC Datasource in Weblogic and using it in the code in a web application

I decided to leverage the Connection pooling features provided by Weblogic in one of the web applications that I wrote. This application uses plain JDBC since dome dynamic capabilities are required for sql statements and so we decided against Hibernate/Spring. Initially the code was written against Open source Snaq DB Connection pooling. Apparently, Weblogic has very good connection pooling features that an application can leverage. Since the code was object oriented and all DAO classes used a DBManager class to get their connection, all I needed to change was a method.

The Weblogic documentation shows how to configure a Data source on Weblogic but has little mention on how to get it working from your web application. The following details should help you set it up. To configure a Data source check the following Weblogic documentation.
In the Data source, I am assuming that you configured the JNDI name as "myAppDbPool"

In your web application, you will need a web.xml entry and an entry in a new file weblogic.xml.

The web.xml entry looks like below


If you don't have a weblogic.xml file in your app create one. It goes in your WEB-INF beside web.xml file. The weblogic.xml file looks like below

<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 8.1//EN"





That's the configuration part. Now all you need to do is code your web application to retreive the Database connection from this Datasource. I made the DBManager class singleton to make sure only one instance runs at a given time. The DBManager class method looks like below:

public Connection getConnection() throws Exception
InitialContext ctx=new InitialContext();
DataSource ds=(DataSource)ctx.lookup("java:comp/env/myAppDbPool");
Connection connection=ds.getConnection();
return connection;

That's it. Use this connection in your DAO and you are all set. But make sure that your DAO object calls connection.close() when it is done accessing the data. According to Weblogic documentation, this returns the connection to the pool for other objects to access it.

If you have better approach or you see any flaws in this, let me know in the comments.


Anonymous said...

Thanks!!! You have earned some goodwill from me!

Anonymous said...

Excellent post... superb
thank you very much, greetings from Colombia!!