Java Developer

Using Tomcat JNDI datasource when deploying Grails production war

When developing a grails application, it is acceptable to hard code the database connection in DataSource.groovy. But when you want to create a war and deploy it on an application server, it is better to use JNDI. This is more flexible because you can change the connection property in the application server, instead of creating a new war.

To do this, in $TOMCAT_HOME/conf/context.xml, put the configuration of the datasource connection and the end of the Context tag. The example below is based on Tomcat6 or Tomcat7, and Grails 2.x:

<?xml version='1.0' encoding='utf-8'?>
<Context>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <Resource name="myDatasourceName" auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000"
        username="root" password="password" driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/my_db_name"/>
</Context>

And in your DataSource.groovy,

dataSource {
    pooled = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = 'org.hibernate.dialect.MySQL5InnoDBDialect'
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
    development {
        dataSource {
            username = "root"
            password = "password"
            dbCreate = "update"
            url = "jdbc:mysql://localhost:3306/my_dev_db_name"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            jndiName = "java:comp/env/myDatasourceName
        }
    }
}

Take note on how I constructed the jndiName. It looks easy, but if you don't get the right naming convention (e.g. it should be prefixed with java:comp/env/), it will not work. Now when you create the war and deploy to Tomcat, it can retrieve the datasource successfully from your application server.
Happy coding!
Tags: datasource, grails, jndi, production, tomcat, war