Tuesday, April 01, 2008

Groovy test ride

" Groovy is an agile and dynamic language for the Java Virtual Machine "


I have been following the Java scripting languages landscape for quite sometime now. I am simply overwhelmed with the sheer number of scriprting languages that can be run off the JVM. I was keenly following one such scripting language with interest - Groovy. I finally decided to take Groovy for a test ride, after reading a lot of interesting stuff on blogs & articles. I decided to try a simple example & see what I can learn from my experiment.

What's the Scenario ?

I have two database tables - EMP ( to keep details of employees ) and DEPT ( to keep details of departments ). I want to pull out details of an employee from the EMP ( Employee Number, Employee Name, Salary ) and DEPT ( Department Name ) tables and store it in another table named EMP_REPORT ( Employee Number, Employee Name, Salary, Department Name )

What am I going to use ?

  • Microsoft Windows XP [Version 5.1]
  • Java 1.5
  • Groovy 1.5.4
  • Oracle Database 10g Enterprise Edition Release 10.1.0.4.2
  • Oracle SQL Developer 1.2.1
What are the logical steps ?

1. Connect : to the Database.
2. Query : the tables EMP and DEPT using a SQL SELECT statement.
3. Results : get the Result Ser
3. Iterate : the result set and get each record.
4. Add : each record to the EMP_RECORDS table.

What about installation ?

The installation procedure for Groovy is very easy - download & unzip. If you have set the JAVA_HOME environment variable to point to your JDK installation directory, you can just proceed to Groovy's /bin directory and double click on GroovyConsole.bat. You can see a simple IDE that allows you to execute your Groovy code. You can use CTRL + R to execute the code and CTRL+W to clear the output window.

... and...What does the Groovy code look like ?

import groovy.sql.Sql
import groovy.xml.MarkupBuilder

def source = Sql.newInstance(
"jdbc:oracle:thin:user/password@host:port:sid",
"oracle.jdbc.driver.OracleDriver"
)

def target = Sql.newInstance(
"jdbc:oracle:thin:user/password@host:port:sid",
"oracle.jdbc.driver.OracleDriver"
)

def sourceEmployees = source.dataSet("EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO")
def targetEmployees = target.dataSet("EMP_REPORT")

sourceEmployees.each
{
targetEmployees.add( ID : it.empno , NAME : it.ename , SAlARY : it.sal , DEPARTMENT : it.dname )
}

My thoughts ?

Well, that was quite easy ! It took less that 10 minutes for me to setup Groovy & try the code. I only faced one problem - Groovy complained that it couldn't find the Database Driver class oracle.jdbc.driver.OracleDriver. I simply put ojdbc14.jar into my JAVA_HOME/jre/ext/lib folder as a workaround.

I found Groovy to be simple & much closer to Java than the other scripting languages touted for the JVM. I think I'll probably use it for prototyping something in Java/JEE in the future.

No comments: