Sunday, May 13, 2012

Connection pool in Tomcat

I like discovery channel, especially on Sunday, I will turn into this channel to watch what are the exciting and interesting news is on the show. Hey! why don't I make my own discovery channel... in JAVA ;) This gonna be more fun and exciting. xD

My solution architect require us to change the JDBC connection to connection pool, how that could be done? So easy, by configuring the datasource name in hibernate. But how is the actual work done in server site? I have no idea because the database we are using is Informix and it is shield by the server admin.

In order for me to carry on the research, I decided to do it using Tomcat. When a new Tomcat server instance is created in Eclipse, look for the context.xml. Put in following code:

< Resource name="jdbc/mydb" auth = "Container" type = "javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="abcd" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/exercise" />

In web.xml, put following code:

< resource-ref >
      < description > DB Connection < /description >
      < res-ref-name > javax.sql.DataSource < /res-ref-name >
      < res-type > javax.sql.DataSource < /res-type >
      < res-auth > Container < /res-auth >
  < /resource-ref >

That's all about it. To test out the code, make a new JSP test page, put in following code.

1st piece of code is to make a query:
< sql:query var="rs" dataSource="jdbc/mydb" >
select FIRSTNAME from CONTACT

2nd piece of code is to render the output:
< c:forEach var="row" items="${rs.rows}" >
    Foo ${ row.FIRSTNAME }< br/ >
< /c:forEach >

No comments: