Java Developer

Understanding Grails dbCreate or hbm2ddl

One of the convenient features of Hibernate that is inherited by Grails, is that once you have defined your data model, it can create the tables for you automatically on start up of the application. The nice thing about this is since Hibernate/GORM is database agnostic, it means you don't need to know how to define the tables in different relational databases. Be it Oracle, DB2, or MySQL. If you change your connection property, and load the appropriate JDBC driver, it will know how to talk to the database and create the correct tables.
In Hibernate, the property you need to define is hbm2ddl. But in Grails, it's dbCreate property in your DataSource.groovy. For example:
environments {
    development {
        dataSource {
            username = "root"
            password = "root"
            dbCreate = "update"
            url = "jdbc:mysql://localhost:3306/awesome_db"
There are 4 values to choose from:
  • create - On startup of your application, this will drop and recreate your schema. This will make sure that you will always have a clean table structure, and all your data is reset on every startup. This is ideal when you are in the early stages of the project and heavily modifying your data model. You will need to spend more time on your Bootstrap though, to create all background data that you need.
  • create-drop - This will behave exactly like create when starting up your application, with addition that it will drop all your tables when the application is shut down properly or gracefully. I have no idea why you would need to do this. I would prefer the create method, because you still have the chance to inspect your database after stopping your application.
  • update - This will not your schema or any of your tables, but will instead try to synch the database with your current data model. This is done by adding the missing tables or columns to your database. In my testing, this will not drop tables or columns from the database when you removed their corresponding items in the data model. It does not guarantee a clean table representation of your data model. This however is ideal when you are in the middle of development, where it is not practical to put most of your test data in the Bootstrap.
  • validate - this will not alter your database, but will just compare your data model with the database on start up. And create warnings if necessary. This is ideal when deploying to production environment.
Tags: database, dbCreate, gorm, grails, hbm2ddl, orm, schema, tables