Reputation: 89
I'm upgrading an application from Grails 2 to Grails 3. In the application I have a Grails service where I need to pick data source based on a url param. So my setup in Grails 2 looks sort of like this (pseudo-code):
application.yml:
development:
dataSource_1_a
dataSource_2_a
dataSource_2_b
test:
dataSource_1_a
dataSource_2_a
dataSource_2_b
FooService.groovy:
Sql getSqlInterface(Environment env) {
switch(env){
case Environment.A:
return new Sql(dataSource_2_a)
case Environment.B:
return new Sql(dataSource_2_b)
default:
throw new Exception("Invalid environment $env!")
}
}
But in Grails 3 I have yet to manage to use two data sources in the same service (with a dataSources
block in application.yml
). If I call one of them dataSource
then that one will work, but not the other one. I know that you can do static mapping = { datasource 'secondary' }
but that also doesn't seem to support multiple data sources.
Upvotes: 0
Views: 1003
Reputation: 89
What worked for me was this:
ApplicationContext context = Holders.grailsApplication.mainContext
switch (env) {
case Environment.A:
return new Sql((DataSource)context.getBean('dataSource_1_a'))
case Environment.B:
return new Sql((DataSource)context.getBean('dataSource_1_b'))
default:
throw new Exception("Invalid environment $env!")
}
Upvotes: 0
Reputation: 466
As you can see here you can add multiple dataSources to your domain Class.
An Service can only have one DataSource, but you could make an Service for each DataSource and one Service that manage the request, like this:
switch(Environment env){
case Environment.A:
return dataSourceAService.method()
case Environment.B:
return dataSourceBService.method()
default:
throw new Exception("Invalid environment $env!")
}
Upvotes: 1