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.
http://edocs.bea.com/wls/docs90/jdbc_admin/jdbc_datasources.html.
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


<resource-ref>
<res-ref-name>myAppDbPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>


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"

"http://www.bea.com/servers/wls810/dtd/weblogic810-web-jar.dtd">

<weblogic-web-app>

<reference-descriptor>
<resource-description>
<res-ref-name>myAppDbPool</res-ref-name>
<jndi-name>myAppDbPool</jndi-name>
</resource-description>
</reference-descriptor>

</weblogic-web-app>


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.

2 comments:

Anonymous said...

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

Anonymous said...

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