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?

asked Nov 5, 2015 at 20:54
\$\endgroup\$

1 Answer 1

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()
answered Nov 8, 2015 at 21:53
\$\endgroup\$
1
  • \$\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\$ Commented Nov 9, 2015 at 16:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.