jckeyes
jckeyes

Reputation: 620

Grails 2 - How to dynamically call multiple datasources

I have two named data sources in my Grails app (Grails 2.0.3)...

dataSource_a {
   // ...
}

dataSource_b {
   // ...
}

I'd like the ability to dynamically change what datasource I'm accessing, based on some kind of parameter. I could do something like this...

def findPeople(datasource) {
    if (datasource == 'a') {
        return Person.a.list()
    } else if (datasource == 'b') {
        return Person.b.list()
    }
}

What I was really hoping to be able to do, though, is something like this...

def findPeople(datasource) {
    return Person."$datasource".list()
}

Unfortunately, I get an error when I try and do that. "Fatal error occurred apply query transformations: null 1 error".

Any thoughts on how to accomplish this? Or am I just stuck with if/switch blocks?

Upvotes: 3

Views: 2162

Answers (1)

jckeyes
jckeyes

Reputation: 620

I figured it out, this is how you have to do it.

def findPeople(datasource) {
    def p = People.class
    p."${datasource}".list()
}

For some reason, if you call it like that, it works.

Upvotes: 4

Related Questions