Added inital methods for the DAO.

This commit is contained in:
Jonathan Bernard 2015-12-14 11:08:32 -06:00
parent e2ba4ab08b
commit 32904e19cd

View File

@ -0,0 +1,103 @@
package com.jdbernard.wdiwtlt.db
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.text.SimpleDateFormat
import com.zaxxer.hikari.HikariDataSource
import groovy.sql.Sql
import groovy.transform.CompileStatic
public class DBv1 {
private HikariDataSource dataSource
private Sql sq
public DBv1(HikariDataSourec dataSource) {
this.dataSource = dataSource
this.sql = new Sql(dataSource) }
public void shutdown() { dataSource.shutdown() }
/// ### Common
public def save(def model) {
if (model.id > 0) return update(model)
else return (create(model)) }
public def update(def model) {
def setClauses = []
def params = []
model.properties
.findAll { it.key != 'class' && it.key != 'id' }
.each {
setClauses << '"' + it.key.replaceAll(
/(\p{javaUpperCase})/, /_$1/).toLowerCase() + '"= ?'
params << it.value }
def sql = new StringBuilder()
.append("UPDATE ")
.append(model.class.name)
.append(" SET ")
.append(setClauses.join(', '))
.append(" WHERE id = ")
.append(model.id)
.toString()
return sql.executeUpdate(sql, params) }
public def create(def model) {
def columns = []
def params = []
model.properties
.findAll { it.key != 'class' && it.key != 'id' }
.each {
setClauses << '"' + it.key.replaceAll(
/(\p{javaUpperCase})/, /_$1/).toLowerCase() + '"'
params << it.value }
def sql = new StringBuilder()
.append("INSERT INTO ")
.append(model.class.name)
.append(" (")
.append(columns.join(', '))
.append(") VALUES (")
.append((1..columns.size()).collect { '?' }.join(', '))
.append(")")
return sql.executeInsert(sql, params) }
public def delete(def model) {
sql.execute("DELETE FROM ${model.class.name} WHERE id = ?", [model.id])
return sql.updateCount }
/// ### Utility functions
static def recordToModel(def record, Class clazz) {
if (record == null) return null
def model = clazz.newInstance()
record.each { recordKey, v ->
def pts = recordKey.toLowerCase().split('_')
def modelKey = pts.length == 1 ? pts[0] :
pts[0] + pts[1..-1].collect { it.capitalize() }.join()
model[modelKey] = v }
return model }
static def modelToRecord(def model) {
if (model == null) return null
def record = [:]
model.properties.each { modelKey, v ->
if (modelKey == "class") return
def recordKey = modelKey.
replaceAll(/(\p{javaUpperCase})/, /_$1/).toLowerCase()
record[recordKey] = v }
return record }
}