Wednesday, December 31, 2008

JDBCTemplate in Grails

Adding Spring's JDBCTemplate support to your grails appliation is really quite painless. This covers adding JDBCTemplate to a test class but this can be extended to any area of the application Edit the file conf\spring\resources.groovy so that it contains the following:
import org.springframework.jdbc.core.JdbcTemplate
import org.apache.commons.dbcp.BasicDataSource
// Place your Spring DSL code here

beans = {
// uses the grails dataSource from DataSource.groovy
jdbcTemplate(JdbcTemplate) {
   dataSource = ref('dataSource')
}

// use a different datasource
otherDataSource(BasicDataSource) {
   driverClassName = "com.mysql.jdbc.Driver"
   url = "jdbc:mysql://localhost:3306/otherDatabase"
   username = "uname"
   password = "pass"
}

otherJdbcTemplate(JdbcTemplate) {
   dataSource = otherDataSource
}
}
Then allow dependency injection to do its work by putting the following at the top of the test class:
class someTests extends GroovyTestCase {
   def jdbcTemplate
   def otherJdbcTemplate
...
}
and finally create a test something like this to exercise the template:
void testJdbcTemplate() {

def myResult = jdbcTemplate.queryForList("select * from table1")
def myOtherResult = otherJdbcTemplate.queryForList("select * from table2")
println "myResult size : ${myResult.size()}"
println "myOtherResult size : ${myOtherResult.size()}"
}