Grails 2 - How to dynamically call multiple datasources

只愿长相守 提交于 2019-11-28 05:24:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10534238/grails-2-how-to-dynamically-call-multiple-datasources

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!