Simpler Stored Procedures with Groovy

Using Groovy almost makes calling Stored Procedures an enjoyable process. See how to process Sql Output Parameters and ResultSets easily in Groovy.

Jeff Sheets

Using Groovy almost makes calling Stored Procedures an enjoyable process. More like a less painful adventure. But since many large enterprises have thousands of stored procedures lying around, at least we can make calling them and using them a bit simpler than the Java counterpart of registering inputs and outputs.

The Groovy Sql class has many features and we’ll focus on two methods of interest for stored procedures: call() to handle output parameters, and rows() to handle ResultSet rows.

Calling an example GetACount stored proc on schema ABC with a lastName input and handling the output parameters is as simple as:

new Sql(dataSource).call("{call ABC.GetACount($lastName, ${Sql.INTEGER})}") { num ->
  println "Num returned $num"
}

Calling a similar FindByFirst that copies the ResultSet rows into a List of GroovyRowResult objects is also straight forward:

List results = new Sql(dataSource).rows("{call ABC.FindByFirst($firstName)}")

Unfortunately the Sql class does not have a method to handle both output parameters AND a ResultSet in the same closure. GROOVY-3048 has been an open feature request since 2008. Until that feature is complete, I’ve created a simple SqlHelper class that adds a callWithRows() method.

First, showing how to use callWithRows() to get the rows and output parameters in a closure. Notice that callWithRows() returns the result of the closure to the original caller for you.

SqlHelper sql = new SqlHelper(dataSource)
List results = sql.callWithRows("{call ABC.FINDBYLAST($lastName, ${Sql.INTEGER}, ${Sql.VARCHAR})}") {
           List<GroovyRowResult> rows, int status, String errorMessage ->
	if (status != 0) {
	  throw new RuntimeException("Error received from stored proc $status : $errorMessage")
	}

	return rows
}

Now here is the source for SqlHelper.groovy. As an extension of Sql.groovy it can reuse many protected helper methods from the super class.

package com.sheetsj.sql

import groovy.sql.GroovyRowResult
import groovy.sql.OutParameter
import groovy.sql.Sql
import groovy.util.logging.Log4j

import java.sql.CallableStatement
import java.sql.Connection
import java.sql.SQLException

import javax.sql.DataSource

/**
 * An extension of groovy Sql class to add a method that can handle
 * stored procedure calls with
 * both output parameters and a ResultSet being returned
 */
@Log4j
class SqlHelper extends Sql {

	SqlHelper(DataSource dataSource) {
		super(dataSource)
	}

	/**
	 * Given a sql with params as GString variables,
	 * will call the given Closure with List of GroovyRowResults similar to Sql.rows()
	 * and the Output variables,
	 * and return the result of the closure
	 * @see http://jira.codehaus.org/browse/GROOVY-3048
	 */
	def callWithRows(GString queryWithParams, Closure closure) {
		log.debug "Calling query $queryWithParams"

		List params = getParameters(queryWithParams)
		String query = asSql(queryWithParams, params)

		Connection conn
		CallableStatement cstmt
		try {
			conn = createConnection()
			cstmt = conn.prepareCall(query);

			setParameters(params, cstmt)
			def hasResultSet = cstmt.execute()

			//Copy resultSet into groovy resultSet rows
			List<GroovyRowResult> rows = []
			if (hasResultSet || cstmt.getMoreResults()) {
				rows = asList(query, cstmt.getResultSet())
			}

			//Set output parameters with rows first
			def outputResults = [rows]
			params.eachWithIndex { param, i ->
				if (param instanceof OutParameter) {
					outputResults << cstmt.getObject(i + 1)
				}
			}

			return closure.call(outputResults.toArray())
		} catch (SQLException e) {
			log.error("Failed to execute $queryWithParams", e)
			throw e
		} finally {
			closeResources(conn, cstmt)
		}
	}
}

Hopefully this was helpful in showing multiple Groovy ways of dealing with the burden of calling Stored Procedures.

Share this Post

Related Blog Posts

JVM

Grails Config Values Per Tomcat Host

December 11th, 2013

An example of using JNDI to provide a Grails application config values per Tomcat Host.

Object Partners
JVM

Guicing up Dropwizard

November 19th, 2013

Implement dependency injection in Dropwizard with Google Guice.

Object Partners
JVM

Parallel Grails Functional Tests with Geb and Gradle

November 14th, 2013

Speed up your Grails functional tests by running them in parallel with Gradle

Object Partners

About the author

Jeff Sheets

Chief Software Technologist

Jeff has developed Java, Groovy, Grails, and Javascript web apps for industries as varied as Defense, Energy, Weather, Insurance, and Telecom. He is a co-organizer of the Omaha Java Users Group. Jeff has worked on Grails projects since the Grails 1.3.x days, and has experience with production Groovy code as well as Spock tests and Gradle builds. His latest focus has been on AngularJS and Spring Boot applications using JHipster. Jeff also enjoys volunteering at local CoderDojo events to teach programming to our next generation.