3

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?

jckeyes
  • 620
  • 1
  • 7
  • 20
  • 1
    Update: I found that it works if you don't inject a variable into the string. So, Person."a".list() works. Doesn't really help me, but interesting nonetheless. – jckeyes May 10 '12 at 12:46
  • if you did want the variable for some reason, it would "${datasource}" instead of "$datasource". – GreyBeardedGeek May 10 '12 at 12:56
  • Actually, you can do simple variable injections in Groovy without the {}... however I get the same result if I do "${datasource}" – jckeyes May 10 '12 at 12:58

1 Answers1

4

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.

jckeyes
  • 620
  • 1
  • 7
  • 20