I am working on a Grails application where I must access several datasources. The datasources are defined in the default database (ie. they are stored there and I must make a call to the default database to retrieve a list of the datasource names I must prepare to connect to). When the server boots up I retrieve the list of databases, create the datasource beans and inject them. All dynamically added databases are structurally identical (ie. have the same table and domain object structure).
This question is the closest I got to a useful piece of code, but it's not quite what I need.
Issue #1
- When I register the datasource beans, they show up where I expect, but Grails does not pick them up.
This is how I add them:
// Register datasource bean
def beanName = 'dataSource_devDB1'
BeanBuilder bb = new BeanBuilder()
bb.beans {
"${beanName}"(BasicDataSource) {
url = "jdbc:h2:devDB1Db;MVCC=TRUE"
pooled = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
}
bb.registerBeans(grailsApplication.mainContext)
// check that it registered
def ctx = grailsApplication.mainContext
def ctxlist = ctx2.beanDefinitionNames.findAll{it.contains( 'dataSource' )}
log.info "ctxlist = " + ctxlist
This prints:
[dataSource, dataSourceUnproxied, dataSource_devDB1]
When I do this, I can execute operations on the default datasource, and that's it.
Issue #2
- If I declare all my datasources as part of the
Datasource.groovy
file, then I can execute operations on all my databases, but not as advertised by the documentation
It works if I do the static mapping on my domain objects:
static mapping = {datasources(['devDB1', 'devDB2', 'DEFAULT')] or datasource = 'ALL'
but what I want is to perform all this as part of a service, and declaring my domain objects to use ALL datasources.
Declaring the datasource in the service is not working:
class secureDBService{
static datasource = "devDB1"
def readWriteMethod(){
.....
// this always uses the default datasource ignoring the static property above.
// the only time it uses devDB1 is if I declare it as part of the domain datasource
// mapping
}
}
This will always use the default datasource no matter what. The only time when it uses the correct datasource is if on the domain object I list the datasource in question.
So, has anyone:
tried adding dynamic datasources and succeeded?
switched between datasources using grails services?
(and this would be a fantastic extra , as a "cherry on top") had success using multiple datasource with spring security core? How do you switch the datasource for the security plugin?
Thanks
--