Posted By

kouphax on 12/03/08


Tagged

groovy orm


Versions (?)

Simple ORM in Groovy


 / Published in: Groovy
 

Using Groovy you can extend the Sql, DataSet and GroovyResultSet objects present in the language to do simple object mapping similar to iBatis et al. An example of using the code below

/* POGO used in the mapping */
class BranchFax {
  def faxCodeId, nsc, faxNumber, branchName, address1
}

/* Connect to the DB */
def db = Sql.newInstance(
    "jdbc:oracle:thin:@//10.7.1.79/DATABSE",
    "user1", "test1",
    "oracle.jdbc.driver.OracleDriver"
)

/* create a dataset */
def bf = db.dataSet("BRANCH_FAX")

/* now work some magic */
def result01 = bf.firstRow().coerce(BranchFax)
def result02 = bf.firstRow().transmogrify(BranchFax)
def result03 = bf.transmogrify(BranchFax)
def result04 = db.transmogrify("SELECT * FROM BRANCH_FAX", BranchFax)
  1. groovy.sql.GroovyRowResult.metaClass.coerce << {Class clazz ->
  2.  
  3. def resultant = clazz.newInstance()
  4. def targetProps = [:]
  5.  
  6. (resultant.properties.keySet() - ["metaClass","class"]).each({
  7. targetProps."${it.toLowerCase()}" = it
  8. })
  9.  
  10. delegate.keySet().each {
  11. def property = targetProps."${it.toLowerCase().replaceAll('_','')}"
  12. resultant."$property" = delegate."$it"
  13. }
  14. }
  15.  
  16. return resultant
  17. }
  18.  
  19. groovy.sql.GroovyRowResult.metaClass.transmogrify << {Class clazz ->
  20. delegate.coerce(clazz)
  21. }
  22.  
  23.  
  24.  
  25. groovy.sql.DataSet.metaClass.transmogrify << {Class clazz ->
  26. delegate.rows().collect {row ->
  27. row.coerce(clazz)
  28. }
  29. }
  30.  
  31.  
  32.  
  33. groovy.sql.Sql.metaClass.transmogrify << {String sql, Class clazz ->
  34.  
  35. delegate.rows(sql).collect {row ->
  36.  
  37. row.coerce(clazz)
  38.  
  39. }
  40.  
  41. }

Report this snippet  

You need to login to post a comment.