Print Shortlink

Multiple data sources in Grails 2.0

One of my favourite features in Grails 2.0 is the support for configuring multiple data sources. I remember playing with the spring resources to configure multiple data sources in one of my client assignments. Grails 2.0 brings in a built-in support for this.
You can go the DataSource.groovy and configure many datasources like below

environments {
    development {
        dataSource {//DEFAULT data source
            
        }
	dataSource_users { //Convention is dataSource_name
            
        }
	dataSource_sales {
            
        }
    }
    production {
        dataSource {
        
	}
	dataSource_users {
            
        }
	dataSource_sales {
            
        }
    }
}

You have 3 datasources configured, the ‘DEFAULT’, ‘users’, ‘sales’ in for development and production environments.
If you have two domain classes ‘Role‘ and ‘Product‘ mapped to table in ‘users’ and ‘sales’ data sources respectively, you can write it as

class Role{
    static mapping = {
          datasource 'users'
    }
}
class Product{
	static mapping = {
		datasource 'sales'
	}
}

If the datasource is not specified in the domain classes it will use the ‘DEFAULT’ datasource.
You need to be careful while using the service classes, because service classes provide transactional support to the default dataSource. You can change it by using static datasource = ‘name of the datasource’ in the service class.

Leave a Reply