问题
I was wondering if we can have 2 datasources configured in a Grails application, I want one to have readonly access (select) and the other to have read-write access (create, insert, update..)
回答1:
For pre-2.0 apps use http://grails.org/plugin/datasources/ and for 2.0 it's built into Grails - see the docs at http://grails.org/doc/2.0.0.RC1/guide/conf.html#multipleDatasources
回答2:
Yes you can but - from my experience - with some conditions/limitations that you should be aware of.
Know this: Grails 2 can't login with spring security when using multiple databases
The documentation http://grails.org/doc/2.0.0.RC1/guide/conf.html#multipleDatasources says that you can switch between datasources either via domain mapping or by using services and the static "datasource" property.
I have found that the domain mapping does work, but the services alone does not work and from the way I interpreted the documentation we should be able to do either.
2.1 Define Datasources in Datasources.groovy: You can declare what datasource you want your domain models to use, that works fine. As well, declare your domain to use several datasources and then specify which datasource to use in your controllers: bookInstance.db1.save() or bookInstance.db2.save()
OR, when the datasource is unknown before hand you can do this:
def ds = "db1" // or set it to anything you want, db1, db2, db3... bookstance."$ds".save()
BUT, if you want to use services to declare the datasource, that does NOT work at all for me.
static datasource = "db1"
No matter what, this has not worked for me in Grails Services.
2.2 Declare Datasource in the default Database and then inject other datasources at runtime. The documentation says that you can inject at runtime a new datasource bean. And you can, but it does not get picked up by Grails. I have not been able to get Grails to be aware of the newly injected datasource beans. So, the datasources MUST be pre-declared in Datasource.grooy
-
来源:https://stackoverflow.com/questions/8159862/can-i-have-2-different-datasources-in-groovy-with-different-privileges