Search code examples
grailsgroovygrails-ormgroovyclassloader

Groovy dynamically invoked class and find method doesn't work?


I trying to build a dynamic query similar to:

def domain = DomainName
def ids = 1
def domainClass = "$domain" as Class
domainClass.find("from ${domain} as m where m.job = ${ids} ").id

But it's not working.

If I'm trying this, all is fine:

def domain = DomainName
def ids = 1
DomainName.find("from ${domain} as m where m.job = ${ids} ").id

How can I use dynamic domain class name with find?


Solution

  • The simplest way is to use the getDomainClass method:

    String domainClassName = 'com.foo.bar.Person'
    def ids = 1
    def domainClass = grailsApplication.getDomainClass(domainClassName).clazz
    domainClass.find("from $domainClassName as m where m.job = ${ids} ").id
    

    Note that if you're trying to get a single instance by id, use get:

    long id = 1234
    def person = domainClass.get(id)
    

    and if you want to get multiple instances and you have a list of ids, you can use getAll

    def ids = [1,2,3,4,5]
    def people = domainClass.getAll(ids)
    

    Also it's a REALLY bad idea to use GStrings with property values embedded - Google 'SQL Injection'

    For example to find a person by username:

    String username = 'foo'
    def person = domainClass.find(
        "from $domainClassName as m where m.username=:username",
        [username: username])