Getting the SessionFactory for a particular Datasource in Grails

走远了吗. 提交于 2019-12-10 15:11:38

问题


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


回答1:


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())



回答2:


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.




回答3:


Better declare the data source in your bean (Service, Controller...) to be injected (no need to depend from Hibernate here)

def dataSource

and use it directly:

Sql sql = new Sql(dataSource)

If you have multiple data sources, just follow the naming convention

def dataSource_foo


来源:https://stackoverflow.com/questions/9028545/getting-the-sessionfactory-for-a-particular-datasource-in-grails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!