Grails - Domain Classes
Vijay Shukla
vijay@nexthoughts.com
Domain Classes
• Object oriented (OO) applications involve a domain model representing the
business entities that the application deals with.
• Domain classes has properties associated with them which map to a
database in order to persist instances of those classes.
• Domain class create : grails create-domain-class <<class_name>>
Persisting Fields to the Database
• All the fields in a domain class are persisted to the database.
• Each field in the class will map to a column in the database.
Validations
• Grails allows you to apply constraints to a domain class that can then be
used to validate a domain class instance.
• Constraints are applied using a "constraints" closure.
• To validate a domain class you can call the "validate()" method on an
instance.
Example
class User {
String login
String password
String email
Date age
static constraints={
login(size:5..15,blank:false,unique:true)
password(size:5..15,blank:false)
email(email:true,blank:false)
age(min:new Date(),nullable:false)
}}
Validating Constraints
def user = new User(params)
if(user.validate()){
//do something
}else{
user.errors.allErrors.each{
Println it
}
}
Custom Validators
class User {
static constraints = {
password(unique:true, length:5..15,
validator{val, obj >
if(val?.equalsIgnoreCase(obj.firstName)){
return false
}
})}}
Transient Properties
• Transient properties are never written to the database.
• Every property in a domain class is persistent and required.
• They don't have a corresponding column in the database.
Example
• class Company {
BigDecimal cash
BigDecimal receivables
BigDecimal getNetWorth() {
cash + receivables
}
static transients = ['netWorth']
}
Custom Mapping
class Person {
String firstName
String lastName
Integer age
static mapping = {
id column:'person_id'
firstName column:'person_first_name'
lastName column:'person_last_name'
age column:'person_age'
version false
}
}
Relationships
• Every table should have at least one relationship to another table.
• The types of relationships that Grails supports are:
• One-to-one
• One-to-many
• Many-to-one
• Many-to-many
One-to-One Relationship
class Car {
Engine engine
}
class Engine {
static belongsTo = [car:Car]
}
One-to-many relationships
class Artist {
String name
static hasMany = [albums:Album]
}
class Album{
static belongsTo[artist:Artist]
}
Many-to-many relationships
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
}
class Author {
static hasMany = [books:Book]
}
Composition in Gorm
If you define the Address class in a separate Groovy file in the
grails-app/domain directory you will also get an address table. If
you don't want this to happen use Groovy's ability to define
multiple classes per file and include the Address class below the
Person class in the grails-app/domain/Person.groovy file
Sets, Lists
Automatic timestamping
If you define a dateCreated property it will be set to the current date for you when you create new instances. Likewise, if you define a
lastUpdated property it will be automatically be updated for you when you change persistent instances.
If this is not the behaviour you want you can disable this feature with:
GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a
list of supported events:
● beforeInsert - Executed before an object is initially persisted to the database. If you return false, the insert will be cancelled.
● beforeUpdate - Executed before an object is updated. If you return false, the update will be cancelled.
● beforeDelete - Executed before an object is deleted. If you return false, the delete will be cancelled.
● beforeValidate - Executed before an object is validated
● afterInsert - Executed after an object is persisted to the database
● afterUpdate - Executed after an object has been updated
● afterDelete - Executed after an object has been deleted
● onLoad - Executed when an object is loaded from the database
To add an event simply register the relevant method with your domain class.
Modification Checking
isDirty:- to check if field is modified
getDirtyPropertyNames:- to retrieve the names of modified fields; this may be empty but will not be null
getPersistentValue:- to retrieve the value of a modified field:
Custom ORM Mapping
MySQL Connectivity
dataSource {
pooled = true
dbCreate = "update"
url = "jdbc:mysql://localhost/yourDB"
driverClassName = "com.mysql.jdbc.Driver"
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
username = "yourUser"
password = "yourPassword"
}
Questions?

Grails domain

  • 1.
    Grails - DomainClasses Vijay Shukla vijay@nexthoughts.com
  • 2.
    Domain Classes • Objectoriented (OO) applications involve a domain model representing the business entities that the application deals with. • Domain classes has properties associated with them which map to a database in order to persist instances of those classes. • Domain class create : grails create-domain-class <<class_name>>
  • 3.
    Persisting Fields tothe Database • All the fields in a domain class are persisted to the database. • Each field in the class will map to a column in the database.
  • 4.
    Validations • Grails allowsyou to apply constraints to a domain class that can then be used to validate a domain class instance. • Constraints are applied using a "constraints" closure. • To validate a domain class you can call the "validate()" method on an instance.
  • 5.
    Example class User { Stringlogin String password String email Date age static constraints={ login(size:5..15,blank:false,unique:true) password(size:5..15,blank:false) email(email:true,blank:false) age(min:new Date(),nullable:false) }}
  • 6.
    Validating Constraints def user= new User(params) if(user.validate()){ //do something }else{ user.errors.allErrors.each{ Println it } }
  • 7.
    Custom Validators class User{ static constraints = { password(unique:true, length:5..15, validator{val, obj > if(val?.equalsIgnoreCase(obj.firstName)){ return false } })}}
  • 8.
    Transient Properties • Transientproperties are never written to the database. • Every property in a domain class is persistent and required. • They don't have a corresponding column in the database.
  • 9.
    Example • class Company{ BigDecimal cash BigDecimal receivables BigDecimal getNetWorth() { cash + receivables } static transients = ['netWorth'] }
  • 10.
    Custom Mapping class Person{ String firstName String lastName Integer age static mapping = { id column:'person_id' firstName column:'person_first_name' lastName column:'person_last_name' age column:'person_age' version false } }
  • 11.
    Relationships • Every tableshould have at least one relationship to another table. • The types of relationships that Grails supports are: • One-to-one • One-to-many • Many-to-one • Many-to-many
  • 12.
    One-to-One Relationship class Car{ Engine engine } class Engine { static belongsTo = [car:Car] }
  • 13.
    One-to-many relationships class Artist{ String name static hasMany = [albums:Album] } class Album{ static belongsTo[artist:Artist] }
  • 14.
    Many-to-many relationships class Book{ static belongsTo = Author static hasMany = [authors:Author] } class Author { static hasMany = [books:Book] }
  • 15.
    Composition in Gorm Ifyou define the Address class in a separate Groovy file in the grails-app/domain directory you will also get an address table. If you don't want this to happen use Groovy's ability to define multiple classes per file and include the Address class below the Person class in the grails-app/domain/Person.groovy file
  • 16.
  • 17.
    Automatic timestamping If youdefine a dateCreated property it will be set to the current date for you when you create new instances. Likewise, if you define a lastUpdated property it will be automatically be updated for you when you change persistent instances. If this is not the behaviour you want you can disable this feature with:
  • 18.
    GORM supports theregistration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events: ● beforeInsert - Executed before an object is initially persisted to the database. If you return false, the insert will be cancelled. ● beforeUpdate - Executed before an object is updated. If you return false, the update will be cancelled. ● beforeDelete - Executed before an object is deleted. If you return false, the delete will be cancelled. ● beforeValidate - Executed before an object is validated ● afterInsert - Executed after an object is persisted to the database ● afterUpdate - Executed after an object has been updated ● afterDelete - Executed after an object has been deleted ● onLoad - Executed when an object is loaded from the database To add an event simply register the relevant method with your domain class.
  • 19.
    Modification Checking isDirty:- tocheck if field is modified getDirtyPropertyNames:- to retrieve the names of modified fields; this may be empty but will not be null getPersistentValue:- to retrieve the value of a modified field:
  • 20.
  • 21.
    MySQL Connectivity dataSource { pooled= true dbCreate = "update" url = "jdbc:mysql://localhost/yourDB" driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect username = "yourUser" password = "yourPassword" }
  • 22.