Wednesday, March 12, 2008

How to config Grails's datasource

As you can see,there is a directory named conf($App_home$/grails-app/conf),it include many configuration file.Today we'll disscuss how to config Grails's datasoure.Because of Grails leverages Hibernate,it supports every database that Hibernate support.Following list the Grails supported database.
• DB2 7.1, 7.2, 8.1
• HSQLDB
• HypersonicSQL 1.61, 1.7.0, 1.7.2, 1.8
• Microsoft SQL Server 2000
• MySQL 3.23, 4.0, 4.1, 5.0
• Oracle 8i, 9i, 10g
• PostgreSQL 7.1.2, 7.2, 7.3, 7.4, 8.0, 8.1
• SAP DB 7.3
• Sybase 12.5 (JConnect 5.5)
• Timesten 5.1
Let me assume that we use postgresql.Then we should download the JDBC driver from postgresql homepage,and copy it into the directoty lib($App_home$/lib).Then edit the file DataSource.groovy in directory conf.like this(I add some comments for every section):
dataSource {
pooled = true //which allows you to configure whether to use a connection pool or not
driverClassName = "org.postgresql.Driver" //the database driver class name
username = "postgres" //database name
password = "123456" //database password
}
//It is the configurate for hibernate,you can change it fit your want.
hibernate {
cache.use_second_level_cache=true
cache.use_query_cache=true
cache.provider_class='org.hibernate.cache.EhCacheProvider'
}
// environment specific settings,there are three database for our application.
//sparrow_dev:for development phase.
//sparrow_test:for test phase.
//sparrow_pro:for product phase.
environments {
development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop','update'
url = "jdbc:postgresql://127.0.0.1:5432/sparrow_dev"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:postgresql://127.0.0.1:5432/sparrow_test"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:postgresql://127.0.0.1:5432/sparrow_pro"
}
}
}

Now,you can run you application under a database model.congratulation.

2 comments:

Anonymous said...

Thanks! That was the config that I was looking for. Quick and easy!

Anonymous said...

why does no-one ever mention that you need to add a dependency in BuildConfig.groovy like this:

grails.project.dependency.resolution = {

dependencies {
runtime "postgresql:postgresql:9.1-901.jdbc4"

}