Thursday, January 22, 2009

JPA Connection Pooling

OpenJPA does not use any kind of connection pooling out of the box, but no worries for those of you using openJPA on WebSphere. When running on WebSphere, the application server provides production-quality connection pooling. That is great if your application runs on WAS, not so great otherwise. Since I haven't found a *good* reason why anyone would run without connection pooling, it seems like a good topic for a first post.

Modifying an existing application to use connection pooling couldn't be easier. To start, you're going to need to download the Apache Commons Pool and DBCP components and add them to your application classpath. Next you will need to update the application database connection properties. Below is an example openJPA configuration using DBCP. You will need to update the connection info where appropriate if using a different DB. Note that these properties are being set in the META-INF/persistence.xml file, but you can also set the JVM system properties directly.

<property name="openjpa.ConnectionDriverName" value="org.apache.commons.dbcp.BasicDataSource"/>
<property name="openjpa.ConnectionProperties" value="DriverClassName=com.mysql.jdbc.Driver,Url=jdbc:mysql://localhost/test,Username=root,Password=password"/>
Configuring openJPA to use connection pooling is as simple as that. I created a small JSE application for this post that uses both pooled and non-pooled connections to do 1000 selects on an empty table. Even though the example is very simple, the results are pretty impressive.
  • 1000 selects with no connection pooling took ~23.469 seconds.
  • 1000 selects with connection pooling took ~1.234 seconds.
-Rick

5 comments:

Chris said...

Simple and working, just what I was looking for.

Many thanks!

Unknown said...

Thank you for the post. Just what I have been looking for. One question, when I run my app I need to provide the following property:
property name="openjpa.RuntimeUnenhancedClasses" value="supported"
Otherwise I get the exception below, any idea why?
Attempt to cast instance "MyEntity" to PersistenceCapable failed. Ensure that it has been enhanced.

Rick Curtis said...

Uma - That message is because you haven't enhanced your Entities. This blog post is a good place to start reading about enhancement.

Unknown said...

Hi Rick Curtis..I am new to connection pooling.The link you have mentioned in your post/blog for the example source code seems to be outdated or unavailable...Can you please share the url from where I can download the example source code

Rick Curtis said...

Swathi -

Unfortunately it looks like that I lost my web hosting. I'll search around my system for the example, but I don't have much luck. This example is over 3 years old. I think that most of the meaningful parts from the example are included in the text of this blog posting. Best of luck!

-Rick