Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Database Resource Handling

DZone's Guide to

Groovy Database Resource Handling

· Database Zone
Free Resource

Download the Guide to Open Source Database Selection: MySQL vs. MariaDB and see how the side-by-side comparison of must-have features will ease the journey. Brought to you in partnership with MariaDB.

I am a big fan of using SQL in java and C# software. I typically dislike the usage of ORM frameworks like Hibernate. I feel that ORMs tend to hide a lot of of issues. They also tend to have a higher learning curve. I am not sure that the ROI on deeply learning an ORM is sufficient enough to use. However, there are a lot of pitfalls that come with being so close to the SQL. The largest of which is proper resource handling. If database connections are not closed properly, the application will soon become starved of available connections.

This post contains a simple example of using Groovy Categories to help manage the resource management of database connections. There are a lot more robust solutions (ie: GORM), but sometimes you only need a quick implementation.

To accomplish our goal, we will be using a static closure defined below. The OpenDatabase class is merely a container for the closure. I think the final implementation of the code reads nicely because of the name.
OpenDatabase.groovy

import groovy.sql.Sql
 
class OpenDatabase {
    def static with = { DbConnection conn, Closure closure ->
        Sql sql
        try {
            sql = conn.getConnection()
 
            if (closure) {
                closure(sql)
            }
        }
        finally {
            sql.close()
        }
    }
}

The DbConnection class is a simple interface for creating the groovy.sql.Sql object.

DbConnection.groovy

import groovy.sql.Sql;
 
public interface DbConnection {
  Sql getConnection();
}

Below is the sample usage of these two classes.

OpenDatabase.with(dbConnector) { sql ->
         sql.execute("insert into BLAH...")
}

The database connection will be closed after closure exits. Simple, easy resource handling. The groovy way.

The original article can be found at http://www.greenmoonsoftware.com/2014/04/groovy-database-resource-handling/ 

Interested in reducing database costs by moving from Oracle Enterprise to open source subscription?  Read the total cost of ownership (TCO) analysis. Brought to you in partnership with MariaDB.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}