Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
jckeyes Avatar asked Jan 30 '26 20:01

jckeyes


1 Answers

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.

like image 130
jckeyes Avatar answered Feb 02 '26 21:02

jckeyes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!