0
\$\begingroup\$

A have a model with a dynamic field like so:

def resolveClient() {
    if (prevCall && prevCall.client) {
        return prevCall.client
    } else {
        return client
    }
}

Pretty simple. However, using a dynamic field makes me unable to do queries at the database level. I can't query using HQL or Criteria. This seems to be impacting performance pretty heavily. What's a better method to do something like this?

\$\endgroup\$
1
\$\begingroup\$

In order to resolve the client with a GORM/Hibernate query you basically need to persist the resolved client value.

Based on your resolveClient() method I'm assuming your domain class model goes something like this:

class SomeDomainClass {
    Call prevCall
    Client client

    def resolveClient() {
        if (prevCall && prevCall.client) {
            return prevCall.client
        } else {
            return client
        }
    }
}

class Call {
    Client
}

class Client { }

If you were dealing with two properties that were in the SomeDomainClass then you'd probably be able to use a derived property. But since one of the properties in an association, a derived property won't work. Instead, you can do this:

class SomeDomainClass {
    Call prevCall
    Client client
    Client resolvedClient

    def resolveClient() {
        prevCall?.client ?: client
    }

    def beforeInsert() {
        resolvedClient = resolveClient()
    }

    def beforeUpdate() {
        resolvedClient = resolveClient()
    }
}

The new property resolvedClient, which is maintained by the beforeInsert() and beforeUpdate() methods, takes care of saving the current resolved client to the GORM store (database). With that value persisted you can use it in GORM queries:

def instances = SomeDomainClass.where {
    resolvedClient == someClient
}.list()

On the Groovy side, it would still be best to use the resolveClient() method because the resolvedClient property can get out of sync if prevCall changes.

def client = instance.resolveClient()
\$\endgroup\$
  • \$\begingroup\$ Thanks, Emmanuel. That's basically what I ended up doing. I already have an update method for my domain, so I just tacked the resolved client onto that. (I also tried calling a stored function from a derived property, but this is an abstract domain class, and apparently GORM or Grails doesn't support derived properties on those :/ ) \$\endgroup\$ – Charles Wood Nov 9 '15 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.