Access POGO/POJO Properties

ᎣᏏᏲ. ᏙᎯᏧ? Hey, welcome back!

I was working with my database and my domain classes have 45 properties. I didn’t want to implement those by hand. If you’re using Grails it will automatically populate the object via GORM. I’m writing some tests to run so I can check my assumptions before I actually run code against the database and populate tables.

The first method is explicitly pulling the fields and populating the data like this:

SQL.eachRow(<sqlquery>) {GroovyResultSet grs ->
    def str = grs.getString("FieldName")

Imagine having to do that for 45 fields. It would be insane for one class… but if you have a whole catalog of classes and they could have any number of fields it becomes unmaintainable.

Using Groovy goodness we can script this a little better. We can declare a list of properties for only a few fields. Again this is just for one class and there’s a slew of switch statements that would need to be used. We don’t want to do that. However, here’s an example:

        def classProperties = ["id", "entrya", "syllabaryb"]
        SQLClass.SQL.eachRow("select * from likespreadsheets where source = 'cwl' and entrya like '%,%'") {grs ->
            def likespreadsheet = new Likespreadsheets()
            //iterate over each explicit property
            classProperties.each {
                // using metaclassing we can reference a property or method using a GString and the value we want. 
                likespreadsheet."$it" = grs.getObject(it)

            lksList << likespreadsheet

        lksList.each {
            println it.entrya
            println it.syllabaryb

Here’s a simpler example:

class MyClass {
    def entrya
    def syllabary
    def transliteration
    def phonetic

def mapping = [:]

mapping.put("entrya", "entry goes here")
mapping.put("syllabary", "syllabary goes here")
mapping.put("transliteration", "transliteration goes here")
mapping.put("phonetic", "phonetic goes here")

def myclass = new MyClass()
mapping.each {key, value ->
    myclass."$key" = value

println myclass.entrya

In this example we have a mapping of values; which is what you’ll have with a result set. We don’t want to spend the time making switch statements or if statements to determine what goes where. Instead. we can pull the key value tell our code that we want that property from the class and give it the value.

Previous MetaClass tutorials:

kind of MetaClass-y

metaClass things to remember

metaClass tips

Until next time. Dodadagohvi. ᏙᏓᏓᎪᎲᎢ.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: