GORM - Creating a domain class

Creating a Domain Class

Basics

A domain class in Grails is essentially a normal Groovy class. It looks like any other class except at runtime it gets injected with 2 additional properties: an "id" property and a "version" property:

Book.groovy
class Book {
    String title
}

To help you get started you can run the following convenience target from the root of your Grails project:

grails create-domain-class

Nullable and Transient properties

By default, all properties are both persistent and required. To change that you can define the List property called "transients" and the constraint "nullable". Transient properties are never written to the database. They don't have a corresponding column in the database. Properties with a "nullable" constraint of true have corresponding columns in the database that are nullable.

Book.groovy
class Book {
    static transients = [ "digitalCopy" ]
    static constraints = {
        releaseDate(nullable: true)
    }

    String author
    String title
    Date releaseDate
    File digitalCopy
}

Default values

You can also create default values for properties that you don't want to make nullable. This is done like so:

Book.groovy
class Book {
    //omitted code...

    String title = ''
    String author = '[author unknown]'
    //etc..
}

This is also helpful when you want to pre-populate form fields when creating new entries.

Changing the Table

You can change the name of the table used with the mapping property:

Book.groovy
class Book {

    static mapping  = {
	table  'book_table'
    }

    String title = ''
}

SQL Reserved Words

Be careful with SQL reserved words. The code bellow will have problem because of the "order" attribute. "order" is a SQL reserved word:

Book.groovy
class Book {
    Integer order
}

Labels

 
(None)