Simpler Stored Procedures with Groovy

Published:
Reading time:
About 2 min

 

(note: This feature has now been added to the Groovy language itself, see the SQL callWithRows and callWithAllRows methods!)

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:

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

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.

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.

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

Cross-published on the Object Partners blog:  https://objectpartners.com/2014/01/24/simpler-stored-procedures-with-groovy/