Sunday, May 3, 2009

Set pojo properties with groovy sql row results

This is probably documented somewhere that you can do this with a Map and a regular typed Object, I just hadn't run across it and tried it to see what happens.

You can just pass in a Map of properties to an Object and as long as you don't have any properties in your Map that are not defined in the class, it'll work fine. As an example:


class Person {
String name
Integer age
String address
}

def map = [ name: "Joe", age: 4, address: "Somewhere"]

Person p = new Person(map)

println "Peson name: $p.name, address: $p.address"


This comes in real handy when want you want to populate some groovy sql results into a collection of typed objects. As an example:


def getPersons() {
def persons = []
sql.eachRow("Select * from Person") {
persons << new Person( it.toRowResult() )
}
return persons
}

1 comment :

  1. def getPersons() {
    sql.eachRow("Select * from Person") {
    new Person( it.toRowResult() )
    }.collect()

    ReplyDelete

Blogger Syntax Highliter