Grails Cookbook - A collection of tutorials and examples

Add MySQL driver jar to a Grails Project using BuildConfig

In the old days, the common way of adding external libraries to a Grails project is by adding the JAR files in the lib folder of your application. This method is easy and simple. But the more modern and recommended way is to utilize BuildConfig.


Grails BuildConfig

BuildConfig is great and easy to understand, specially if you are familiar with Maven. You only need to specify what you want, and Grails will download the required JAR files for your, including dependencies if any.

To add MySQL, open your BuildConfig.groovy file and add an entry to the dependencies section:

dependencies {
    runtime 'mysql:mysql-connector-java:5.1.29'
}

The MySQL driver jar will be loaded when you run your Grails application in development mode. It will also be included in the war file when you create a war out of your Grails application.

MySQL

To connect to a MySQL server, you also need to edit your DataSource.groovy to the correct connection url, db user, and db user password. For example:

dataSource {
	pooled = true
	driverClassName = "com.mysql.jdbc.Driver"
	dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
environments {
    development {
        dataSource {
            dbCreate = "create-drop"
            url = "jdbc:mysql://localhost/test"
            username = "admin"
            password = "mysecretadminpassword"
        }
    }
    test {
        dataSource {
            ...
        }
    }
    production {
        dataSource {
            ...
        }
    }
}

Now your application can talk to a MySQL database
Tags: BuildConfig, jar, MySQL