concept DbHelper in category groovy
appears as: The DbHelper, DbHelper

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.
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 } }