Last updated by lmlsky
2 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"
}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" /> </bean>
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.GrailsApplicationbeans = { switch(GrailsUtil.environment) { case GrailsApplication.ENV_PRODUCTION: log.info "creating my special production Jndi datasource" mySpecialDatasource(JndiObjectFactoryBean) { jndiName = "myJndiName" } break default: log.info "creating my special development/test datasource" mySpecialDatasource(BasicDataSource) { driverClassName = "com.ibm.db2.jcc.DB2Driver" url = "jdbc:db2://mydb2serverIP:port/databasename" username = "userid" password = "password" } break }
def mySpecialDatasource
Sql sql = new Sql(mySpecialDatasource) sql.execute("select * from whatever")
Note: This feature is available since Grails 0.3 (see http://jira.codehaus.org/browse/GRAILS-272)