Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the SessionFactory for a particular Datasource in Grails

So if I want to do a direct SQL query using the session that Grails is using prior to supporting multiple datasources I could do:

def conn = new Sql(sessionFactory.currentSession.connection())

Now the question is that I have multiple datasources and want to grab a connection to a specific one.

How do I do that?

TIA

like image 481
user1085751 Avatar asked Jan 27 '12 03:01

user1085751


2 Answers

Given a datasource defined in DataSource.groovy as "dataSource_foo", you'll have a SessionFactory called sessionFactory_foo. So you can dependency-inject it like any other Spring bean:

def sessionFactory_foo

and use it like this:

def conn = new Sql(sessionFactory_foo.currentSession.connection())
like image 138
Burt Beckwith Avatar answered Oct 12 '22 07:10

Burt Beckwith


You can bind to the session using a Domain class reference as follows:

Book.withSession { session -> 
    def conn = new Sql(session.connection())
    ...
}

This method does not require a hardcoded reference to the datasource suffix.

like image 33
James Allman Avatar answered Oct 12 '22 07:10

James Allman