May 01, 2014 Snippet comments
The most common way to configure database access in Grails is to hard code the connection properties inside Datasource.groovy. This is great for development purposes. But for production, we want a flexible way where admins can change which database to connect to, without needing to recompile the application.
The standard way of doing this is to leverage JNDI. We configure the database connection in the application server, and pass it to our Grails application. Below is an example on how to do it with Tomcat.
Configure Tomcat
Pick a name for the JNDI that you will use. In this example, we pick the name
exampleDatasource. To configure Tomcat, edit your TOMCAT_HOME/conf/context.xml. And add a section in the bottom of Context tag:
<Context>
...
<Resource name="exampleDatasource" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="exampleuser" password="secret" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/exampledb"/>
</Context>
If you are new to Tomcat, you need to copy the proper JDBC driver to the TOMCAT_HOME/lib folder. For example, if we use MySQL, copy "mysql-connector-java-5.x.xx-bin.jar" to the TOMCAT_HOME/lib folder:
Configure Datasource.groovy
Using JNDI is sensible for production environment. Edit your Datasource.groovy and configure as follows:
dataSource {
...
}
hibernate {
...
}
environments {
development {
dataSource {
...
}
}
test {
dataSource {
...
}
}
production {
dataSource {
dbCreate = "update"
jndiName = "java:comp/env/exampleDatasource"
}
}
}
Now you can create your war and deploy to your Tomcat server: