Java Reference
In-Depth Information
Lessons learned (JDBC)
1
. JDBC is a very verbose, low-level set of classes for SQL access to relational data-
bases.
Groovy is not available.
Years ago this was the only realistic option for Java. Now other options exist, like Spring's
JdbcTemplate
(discussed in
chapter 7
on Spring) and object-relational mapping tools
like Hibernate (discussed later in this chapter). Still, if you already know SQL and you
want to implement a DAO interface, Groovy provides a very easy alternative: the
groovy.sql.Sql
class.
8.2. The Groovy approach, part 1: groovy.sql.Sql
The
groovy.sql.Sql
class is a simple façade over JDBC. The class takes care of re-
source management for you, as well as creating and configuring statements and logging er-
rors. It's so much easier to use than regular JDBC that there's never any reason to go back.
The next listing shows the part of the class that sets up the connection to the database and
initializes it.