a peek into my MIND

November 18, 2009

Connecting to multiple datasources in grails application

Filed under: Groovy & Grails — Bharat Kondeti @ 7:44 pm

Grails inherently doesn’t support multiple data sources. We cannot specify for example like domain objects D1 and D2 should talk to DataSource1 and rest should talk to Datasource2.

To have this kind of flexibility one has to install Datasources Plug-in into the application.

Once installed create a Datasources.groovy file under configuration directory of the application. This groovy file will be a companion file for DataSource.groovy file.

Now we can add as many data-sources as we want in the new Darasource.groovy file as follows.


datasources = {
  datasource(name: 'aaaaDev') {
    domainClasses([D1,D2])
    driverClassName('com.mysql.jdbc.Driver')
    environments(['development'])
    url('jdbc:mysql://aaaa:3306/aaa')
    username('xxxxxx')
    password('xxxxx')
    dialect(org.hibernate.dialect.MySQL5InnoDBDialect)
    hibernate {
      cache {
        use_second_level_cache(true)
        use_query_cache(true)
      }
    }
  }
  datasource(name: 'aaaaTest') {
    domainClasses([D1,D2])
    driverClassName('com.mysql.jdbc.Driver')
    environments(['test'])
    url('jdbc:mysql://aaaa:3306/aaa')
    username('xxxxxx')
    password('xxxxx')
    dialect(org.hibernate.dialect.MySQL5InnoDBDialect)
    hibernate {
      cache {
        use_second_level_cache(true)
        use_query_cache(true)
      }
    }
  }
}

Couple of interesting tags are domainClasses and environments.

domainClasses take in a list of domain classes.
environments take in a list of environments this data source will be applicable for.

The domain classes that are not listed in this file will use the default data-source defined in DataSource.groovy.

Once this information is defined in the new Datasources.groovy everything will work magically.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: