Developer
Developer

Reputation: 53

Grails Change data base URL connection from session

I need to change the url of data source using session or change current connection to new connection or build new data source at runtime (in my controller or service)

if any one can tell me another way exclude multi data source tell me

Thank you

Upvotes: 1

Views: 852

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75681

I have an approach that's not the cleanest, but should work. If you get access to the dataSource Spring bean you can change its properties. You need to get it to close all pooled connections and then new connections will use the new settings.

You can get to the datasource using dependency injection like any bean, i.e. def dataSourceUnproxied. You have to use "dataSourceUnproxied" instead of "dataSource" to get at the real DataSource, not the transaction-aware proxy that Grails wraps the real one with.

Having done that you can change the url, username, etc. like this:

dataSourceUnproxied.url = 'some other url'
dataSourceUnproxied.username = 'some other username'

Then close it to force all connections to close, but reset the closed flag to trick it into re-connecting the next time getConnection() is called:

dataSourceUnproxied.close()
dataSourceUnproxied.closed = false

This is very specific to the pool implementation since the DataSource interface only has a few methods. This works with the org.apache.commons.dbcp.BasicDataSource that Grails uses by default but if you're using a different pool implementation you'll need to look at its source for an equivalent approach.

Upvotes: 3

Related Questions