Search code examples
grailsgrails-plugingrails-2.0

How to tell a Grails plugin to use a secondary datasource (not the default one)?


I have created a plugin that is responsible for RDBMS access to a secondary datasource this way we hide the domain and service layer from the application that is going to use it (it impedes them from modifying that source). I have the plugn published to artifactory and then imported it successfully into my application. However, the datasource file that the plugin uses got excluded from packaging and when calling the service methods in the plugin it's trying to execute those queries against my default datasource.

  1. Is there a way to tell the grails plugin to not use the default datasource but a secondary datasource? or is there a way to have the plugin not exclude its own DataSource.groovy file?

Thanks

UPDATE

The answer provided below would work, basically that is how multiple data sources work in Grails. The only drawback to that is that when I am developing the plugin itself and I want to run it as an app to make sure it does what I want the datasource that grails expects must be called dataSource so I have to comment out the

static mapping = {
  // datasource 'dataSource_lookup'
}

in order to be able to run it. Then when i see that every thing is good as I desire and I want to publish the plugin I have to go trhough all of my domain files and uncomment the line above so that when the plugin is imported into my main app it will have a reference to the secondary data source. However, this is very very painful and slow.

Is there a better way to do this? Why does the default datasource have to be called dataSource? can that be changed?


Solution

  • In Domain Classes of your plugin you have to do something like this

    static mapping ={
        //if you need to use the second ds only in Production you can use the Environment
        if(Environment.PRODUCTION){
            datasource('your_sencondary_datasource')
        }
    }
    

    and in your principal application in your Datasource.groovy you need to map your datasource like this

    production{
        dataSource {
            <'your configs of primary ds'>
        }
    
        dataSource_you_secondary_datasource {
            <'your configs to secondary ds'>
        }
    }