concept DbHelper in category groovy

appears as: The DbHelper, DbHelper
Groovy in Action, Second Edition

This is an excerpt from Manning's book Groovy in Action, Second Edition.

The infrastructure contains helpers and DAOs. For our example, we have a single helper class DbHelper, an AthleteDAO, and a general abstract DataAccessObject as depicted in figure 13.5.

Figure 13.5. UML class diagram of the athlete example’s infrastructure layer

The DbHelper is responsible for providing access to an instance of groovy.sql.Sql through its db property and setting it to a default value. The second responsibility is to support automatic schema creation by executing the DDL for a given DataAccessObject.

Listing 13.21. Athlete example infrastructure: DbHelper
package layering import groovy.sql.Sql import groovy.text.SimpleTemplateEngine as STE import org.hsqldb.jdbc.JDBCDataSource class DbHelper { Sql db DbHelper() { db = new Sql(new JDBCDataSource( database: 'jdbc:hsqldb:mem:GinA', user: 'sa', password: '')) } def simpleTemplate = new STE().createTemplate(''' DROP TABLE $name IF EXISTS; CREATE TABLE $name ( ${lowname}Id INTEGER GENERATED BY DEFAULT AS IDENTITY, $fields ); ''') def executeDdl(DataAccessObject dao) { def template = simpleTemplate def binding = [ name: dao.tablename, lowname: dao.tablename.toLowerCase(), fields: dao.schema.collect { key, val -> " ${key.padRight(12)} $val" }.join(",\n") ] def stmt = template.make(binding).toString() db.execute stmt } }

At first glance, this may look like an oversimplification of SQL table definitions, because we don’t have to deal with foreign keys or other constraints, views, joins, and so forth. But it would be easy to expand DbHelper to also cover those scenarios by providing correspondingly amended templates.