Monday, December 1, 2008

Working with JDBC datasources with Maven2

During my career I've seen too many database-driven maven2 projects that use maven 2 filtering of resources for jdbc properties in order to externalize the username, password, jdbc url and other JDBC specific configuration to $USER/.m2/settings.xml. The problem with this approach is that we become locked-in to maven2 and won't be able to run a simple JUnit test without first running "mvn clean install", so that the placeholders in jdbc properties file get replaced with the appropriate values from settings.xml.

In my opinion, jdbc properties file should be avoided at all if possible. In a web application for example, it's possible to create a datasource at the container (e.g. Tomcat) and then reference this datasource from the application via JNDI. By doing this, we can happily use JDBC datasources without having to run "mvn clean install", making the life for those folks building inside Eclipse much easier.

Now, we don't always want to run our code inside a container. One such example is when we are running unit tests. For those cases we should create a base JUnit class that is specific to our module, say "MyProjectModuleTestCase" and inject JNDI datasource as explained in Randy Carver's blog post Injecting JNDI datasources for JUnit Tests outside of a container.

No comments: