Back Home

Getting Started

  • grails create-domain-class Foo will create a domain class and test class
  • this automatically maps back to the database with two implicit database columns
    • - the default primary key
    • Foo.version - each save increments the version number, this is used for optimistic locking to workout the latest version
  • Gorm has some default caching, to ensure immediate flush one uses


  • Gorm supports inheritance to provide object modelling e.g
  Class Product 
  Class Book extends Product 

Internally Gorm creates one table Product with columns for Book

Not Stored Data

Object can have data that is not persisted in the database

static transients = ['frood', 'notStored']

LastCreated and LastUpdated

Adding dateCreate and lastUpdate will mean Gorm will automatically update the date values on creation and updates

Date dateCreate, lastUpdated

BeforeInsert, BeforeUpdate, BeforeDelete, onLoad

if provided the following methods will be triggered on the gorm evens

  • beforeInsert, beforeUpdate, beforeDelete, onLoad


Objects can include other objects:

class Product 
String code 

class Book 
Product p 

using it

Product myProduct = new Product()
p.code = "1234"
Book myBook = new Book()
myBook.p = myProduct
// order of save is important

Saving in the wrong order can cause a transient error and this can happen only on the flush

Embedded Classes

Domain classes can embedded information without having to a join (they are stored in the same table)

class Extra
String someExtraValue
class MyDomain 
static embedded bar = ['myExtra']
Extra myExtra

One to One and One to Many Relationships

One to one:

class Father 
  Child child 
class Child 
  static belongsTo = [parent:Father]

One to many is very similar

class Brother 
  static hasMany = [sisters:Sister]
class Sister
  static belongsTo = [parent:Brother]

Tree Relationships


Gorm has a

static constraints = {

Gorm has a range of constraints:

Constraint Description Example
blank Validates that a String value is not blank login(blank:false)
creditCard Validates that a String value is a valid credit card number cardNumber(creditCard: true)
email Validates that a String value is a valid email address. homeEmail(email: true)
inList Validates that a value is within a range or collection of constrained values. name(inList: [“Joe”, “Fred”, “Bob”])
matches Validates that a String value matches a given regular expression. login(matches: “[a-zA-Z]+”)
max Validates that a value does not exceed the given maximum value. age(max: new Date()) price(max: 999F)
maxSize Validates that a value's size does not exceed the given maximum value. children(maxSize: 25)
min Validates that a value does not fall below the given minimum value. age(min: new Date()) price(min: 0F)
minSize Validates that a value's size does not fall below the given minimum value. children(minSize: 25)
notEqual Validates that that a property is not equal to the specified value login(notEqual: “Bob”)
nullable Allows a property to be set to null - defaults to false. age(nullable: true)
range Uses a Groovy range to ensure that a property's value occurs within a specified range age(range: 18..65)
scale Set to the desired scale for floating point numbers (i.e., the number of digits to the right of the decimal point) salary(scale: 2)
size Uses a Groovy range to restrict the size of a collection or number or the length of a String. children(size: 5..15)
unique Constrains a property as unique at the database level login(unique: true)
url Validates that a String value is a valid URL. homePage(url: true)
validator Adds custom validation to a field. See documentation

Customizing Types

Some times the default Java to Sql type mapping is not appropriate so it is possible to define the Java → Hibernate → Sql mapping that occurs

Customizing Identity (Ids and Keys)

The id column is used as the primary key for each table and it’s defined as an auto-increment column

For one-to-many relationships, the child table will include a column to hold the ID of the parent record. The column is named using the name of the parent domain class and declares a foreign key constraint referring back to the parent table.

Identity Algorithm Description
increment numeric id that counts up (!) not safe if more than one process is doing the inserts
identity user the identity column type. Not all databases have such a column type
sequence use a sequence on the database.Not all databases have a sequence
hilo use a table in the database to generate values efficiently
seqhilo use a sequnce in the database to generate values efficiently
uuid generate a uuid for each value
guid gnerate guid for each value Not all databases have this
native pick one of /identity, sequence/ or /hilo/ based on database support
assigned hand of responsibitly of id generation to the user
select use a select on a database trigger to produce a primary key
foreign Intend for a one to one primary key relationship, this uses the identifier of an associated object
class MyTable {
  String stock
  static mapping = {
    id column : 'stock',
    id generator : 'assigned'    
=== Composite Identifier/Key == 
One or more columns can be used as a key 
<code groovy> 
class CompositeKeyClass implements Serializable }
 String code1, code2
 static mapping = {
     id composite:[code1, code2]

Customized Fetch Mode

static fetchMode = [someOtherAttribute : ‘eager’]


  • get get object by id
  • getAll(list of ids) takes a list of variable arguments in order
  • list
Foo.list(sort:'name', ignoreCase:false)

  • listOrderBy
  • findBy and findAllBy
  • findByNameOrRank
gorm.txt · Last modified: 2014/06/24 00:01 by root
RSS - 200 © CrosswireDigitialMedia Ltd