Last updated by lmlsky 3 years ago

JNDI Data Sources

Configuring a JNDI data source

Since Grails 1.0, If you need to look-up a JNDI data source you can specify the data source's JNDI name in the grails-app/conf/DataSource.groovy file as follows:

dataSource {
    jndiName = "java:comp/env/myDataSource"

You then need to configure your container to register a JNDI resource for the specified name (in this case "myDataSource")

Using JNDI DataSources through Spring's resources.xml

 Normally you would use this approach if running inside a J2EE server which has its own JNDI entries for the Database already set up, so you could re-use the connection settings. If there is a bean by name "dataSource" with class "org.springframework.jndi.JndiObjectFactoryBean", Grails runtime would take this entry instead of the grails-app/conf/ datasources.

An example entry for dataSource bean in the resources.xml (grails-app/conf/spring/resources.xml in 0.6 and above) would be as following. Of course you have to change the property jndiName's value appropriately.

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/myDataSource" />

Using both JNDI and "normal" datasource via beanbuilder and resources.groovy

This will configure an additional datasource that will use the commons dbcp datasource for local dev/test and JNDI for production. This is useful if you have multiple datasources and you need to switch to JNDI when you deploy to application server.

import org.apache.commons.dbcp.BasicDataSource
import org.springframework.jndi.JndiObjectFactoryBean
import grails.util.GrailsUtil
import org.codehaus.groovy.grails.commons.GrailsApplication

beans = { switch(GrailsUtil.environment) { case GrailsApplication.ENV_PRODUCTION: "creating my special production Jndi datasource" mySpecialDatasource(JndiObjectFactoryBean) { jndiName = "myJndiName" } break

default: "creating my special development/test datasource" mySpecialDatasource(BasicDataSource) { driverClassName = "" url = "jdbc:db2://mydb2serverIP:port/databasename" username = "userid" password = "password" } break


This creates a an additional datasource with a name of mySpecialDatasource, so if you had a service or controller that needed to access it, you would add the following line to your controller/service

def mySpecialDatasource
Grails/Spring will autowire this datasource to your class and you can then run arbitrary SQL inside a method by simply adding a line like
Sql sql = new Sql(mySpecialDatasource)
sql.execute("select * from whatever")

Note: This feature is available since Grails 0.3 (see