SlideShare a Scribd company logo
1 of 22
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?

More Related Content

Similar to Grails domain

Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...jaxLondonConference
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84Mahmoud Samir Fayed
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsTawnaDelatorrejs
 
Learn java
Learn javaLearn java
Learn javaPalahuja
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdffashionscollect
 
Core Java Programming Language (JSE) : Chapter VI - Class Design
Core Java Programming Language (JSE) : Chapter VI - Class DesignCore Java Programming Language (JSE) : Chapter VI - Class Design
Core Java Programming Language (JSE) : Chapter VI - Class DesignWebStackAcademy
 
You are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfYou are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfeyebolloptics
 
The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 86 of 212
The Ring programming language version 1.10 book - Part 86 of 212The Ring programming language version 1.10 book - Part 86 of 212
The Ring programming language version 1.10 book - Part 86 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210Mahmoud Samir Fayed
 
Inside Gorm
Inside GormInside Gorm
Inside Gormkrimple
 
Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Neo4j
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreRyan Morlok
 
Exercise1[5points]Create the following classe
Exercise1[5points]Create the following classeExercise1[5points]Create the following classe
Exercise1[5points]Create the following classemecklenburgstrelitzh
 

Similar to Grails domain (20)

Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment Instructions
 
Learn java
Learn javaLearn java
Learn java
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
 
Gorm
GormGorm
Gorm
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Core Java Programming Language (JSE) : Chapter VI - Class Design
Core Java Programming Language (JSE) : Chapter VI - Class DesignCore Java Programming Language (JSE) : Chapter VI - Class Design
Core Java Programming Language (JSE) : Chapter VI - Class Design
 
You are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfYou are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdf
 
The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181
 
The Ring programming language version 1.10 book - Part 86 of 212
The Ring programming language version 1.10 book - Part 86 of 212The Ring programming language version 1.10 book - Part 86 of 212
The Ring programming language version 1.10 book - Part 86 of 212
 
Overview of Java
Overview of Java Overview of Java
Overview of Java
 
Introduction To Grails
Introduction To GrailsIntroduction To Grails
Introduction To Grails
 
The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210
 
Inside Gorm
Inside GormInside Gorm
Inside Gorm
 
Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queries
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
 
Exercise1[5points]Create the following classe
Exercise1[5points]Create the following classeExercise1[5points]Create the following classe
Exercise1[5points]Create the following classe
 

More from Vijay Shukla (19)

Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
 
Jython
JythonJython
Jython
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
Groovy
GroovyGroovy
Groovy
 
Grails services
Grails servicesGrails services
Grails services
 
Grails plugin
Grails pluginGrails plugin
Grails plugin
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Grails
GrailsGrails
Grails
 
Controller
ControllerController
Controller
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Command object
Command objectCommand object
Command object
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Vertx
VertxVertx
Vertx
 
Custom plugin
Custom pluginCustom plugin
Custom plugin
 
Spring security
Spring securitySpring security
Spring security
 
REST
RESTREST
REST
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
 
GORM
GORMGORM
GORM
 

Recently uploaded

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Recently uploaded (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Grails domain

  • 1. Grails - Domain Classes Vijay Shukla vijay@nexthoughts.com
  • 2. 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>>
  • 3. 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.
  • 4. 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.
  • 5. 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) }}
  • 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 • 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.
  • 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 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
  • 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 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
  • 17. 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:
  • 18. 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.
  • 19. 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:
  • 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" }