SlideShare a Scribd company logo
Advanced GORM
Topics
● Events and Auto Timestamping
● Custom ORM mapping
● Default Sort Order
● Validations and Constraints
Events and Auto Timestamping
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.
Example - The beforeInsert event
Fired before an object is saved to the database
class Person {
private static final Date NULL_DATE = new Date(0)
String firstName
String lastName
Date signupDate = NULL_DATE
def beforeInsert() {
if (signupDate == NULL_DATE) {
signupDate = new Date()
}
}
}
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.
class Person {
Date dateCreated
Date lastUpdated
}
Custom ORM mapping
Custom mappings are defined using a static mapping block defined within your domain class:
class Person {
…
static mapping = {
version false
autoTimestamp false
}
}
You can also configure global mappings in application.groovy (or an external config file) using this setting:
grails.gorm.default.mapping = {
version false
autoTimestamp false
}
Table and Column Names
Table names
The database table name which the class maps to can be customized using the table method:
class Person {
...
static mapping = {
table 'people'
}
}
In this case the class would be mapped to a table called people instead of the default name of person.
Column names
It is also possible to customize the mapping for individual columns onto the database. For example to change
the name you can do:
class Person {
String firstName
static mapping = {
table 'people'
firstName column: 'First_Name'
}
}
Here firstName is a dynamic method within the mapping Closure that has a single Map parameter. Since its
name corresponds to a domain class persistent field, the parameter values (in this case just "column") are used
to configure the mapping for that property.
Column type
GORM supports configuration of Hibernate types with the DSL using the type attribute. This includes specifying
user types that implement the Hibernate org.hibernate.usertype.UserType interface, which allows complete
customization of how a type is persisted.
class Address {
String number
String postCode
static mapping = {
postCode type: 'text'
}
}
Many-to-One/One-to-One Mappings
In the case of associations it is also possible to configure the foreign keys used to map associations. In the
case of a many-to-one or one-to-one association this is exactly the same as any regular column. For example
consider the following:
class Person {
String firstName
Address address
static mapping = {
table 'people'
firstName column: 'First_Name'
address column: 'Person_Address_Id'
}
}
One-to-Many Mapping
class Person {
static hasMany = [addresses: Address]
static mapping = {
addresses column: 'Person_Address_Id'
}
}
If you don’t want the column to be in the address table, but instead some intermediate join table you can use
the joinTable parameter:
class Person {
static hasMany = [addresses: Address]
static mapping = {
addresses joinTable: [name: 'Person_Addresses',
key: 'Person_Id',
column: 'Address_Id']
}
}
Many-to-Many Mapping
GORM, by default maps a many-to-many association using a join table.To change the column names you can
specify a column within the mappings for each class.
class Group {
...
static hasMany = [people: Person]
static mapping = {
people column: 'Group_Person_Id'
}
}
class Person {
...
static belongsTo = Group
static hasMany = [groups: Group]
static mapping = {
groups column: 'Group_Group_Id'
}
Many-to-Many Mapping
You can also specify the name of the join table to use:
class Group {
...
static mapping = {
people column: 'Group_Person_Id',
joinTable: 'PERSON_GROUP_ASSOCIATIONS'
}
}
class Person {
...
static mapping = {
groups column: 'Group_Group_Id',
joinTable: 'PERSON_GROUP_ASSOCIATIONS'
}
}
Default Sort Order
You can sort objects using query arguments such as those found in the list method:
def airports = Airport.list(sort:'name')
class Airport {
...
static mapping = {
sort "name"
}
}
class Airport {
...
static mapping = {
sort name: "desc"
}
}
Finally, you can configure sorting at the association level:
class Airport {
...
static hasMany = [flights: Flight]
static mapping = {
flights sort: 'number', order: 'desc'
}
}
In this case, the flights collection will always be sorted in descending order of flight number.
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.
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)
}
}
Validations
Validating Constraints
def user = new User(params)
if(user.validate()){
//do something
} else {
user.errors.allErrors.each{
Println it
}
}
Custom Validators
class Response {
Survey survey
Answer answer
static constraints = {
survey blank: false
answer blank: false, validator: { val, Response obj -> val in obj.survey.answers }
}
}
The obj argument to the custom validator is the domain instance that is being validated, so we can access its
survey property and return a boolean to indicate whether the new value for the answer property, val, is valid.
References
● http://gorm.grails.org/latest/hibernate/manual/index.html#advancedGOR
MFeatures
● http://gorm.grails.org/latest/hibernate/manual/index.html#_constraints_r
eference

More Related Content

What's hot

Vectors data frames
Vectors data framesVectors data frames
Vectors data frames
FAO
 
5. working on data using R -Cleaning, filtering ,transformation, Sampling
5. working on data using R -Cleaning, filtering ,transformation, Sampling5. working on data using R -Cleaning, filtering ,transformation, Sampling
5. working on data using R -Cleaning, filtering ,transformation, Sampling
krishna singh
 
3 R Tutorial Data Structure
3 R Tutorial Data Structure3 R Tutorial Data Structure
3 R Tutorial Data Structure
Sakthi Dasans
 
Descriptive Statistics with R
Descriptive Statistics with RDescriptive Statistics with R
Descriptive Statistics with RKazuki Yoshida
 
Chapter15 structure
Chapter15 structureChapter15 structure
Chapter15 structureDeepak Singh
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORM
Saurabh Dixit
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structuresTAlha MAlik
 
Stata Cheat Sheets (all)
Stata Cheat Sheets (all)Stata Cheat Sheets (all)
Stata Cheat Sheets (all)
Laura Hughes
 
R getting spatial
R getting spatialR getting spatial
R getting spatial
FAO
 
Creating a database
Creating a databaseCreating a database
Creating a databaseRahul Gupta
 
Sql queries - Basics
Sql queries - BasicsSql queries - Basics
Sql queries - Basics
Purvik Rana
 
Greenplum 6 Changes
Greenplum 6 ChangesGreenplum 6 Changes
Greenplum 6 Changes
VMware Tanzu
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
Sakthi Dasans
 
R training3
R training3R training3
R training3
Hellen Gakuruh
 

What's hot (15)

Vectors data frames
Vectors data framesVectors data frames
Vectors data frames
 
5. working on data using R -Cleaning, filtering ,transformation, Sampling
5. working on data using R -Cleaning, filtering ,transformation, Sampling5. working on data using R -Cleaning, filtering ,transformation, Sampling
5. working on data using R -Cleaning, filtering ,transformation, Sampling
 
3 R Tutorial Data Structure
3 R Tutorial Data Structure3 R Tutorial Data Structure
3 R Tutorial Data Structure
 
Descriptive Statistics with R
Descriptive Statistics with RDescriptive Statistics with R
Descriptive Statistics with R
 
Chapter15 structure
Chapter15 structureChapter15 structure
Chapter15 structure
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORM
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
 
Stata Cheat Sheets (all)
Stata Cheat Sheets (all)Stata Cheat Sheets (all)
Stata Cheat Sheets (all)
 
R getting spatial
R getting spatialR getting spatial
R getting spatial
 
Creating a database
Creating a databaseCreating a database
Creating a database
 
Chap 10(structure and unions)
Chap 10(structure and unions)Chap 10(structure and unions)
Chap 10(structure and unions)
 
Sql queries - Basics
Sql queries - BasicsSql queries - Basics
Sql queries - Basics
 
Greenplum 6 Changes
Greenplum 6 ChangesGreenplum 6 Changes
Greenplum 6 Changes
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
 
R training3
R training3R training3
R training3
 

Similar to Advance GORM

Grails domain
Grails domainGrails domain
Grails domain
Vijay Shukla
 
Gorm
GormGorm
Gorm
GormGorm
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)
Davide Rossi
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)Jerome Eteve
 
GORM
GORMGORM
GORM
GORMGORM
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4Vince Vo
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Grails basics part2
Grails basics  part2Grails basics  part2
Grails basics part2
Saurabh Dixit
 
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
fashionscollect
 
XQuery Triggers in Native XML Database Sedna
XQuery Triggers in Native XML Database SednaXQuery Triggers in Native XML Database Sedna
XQuery Triggers in Native XML Database Sednamaria.grineva
 
05-OOP-Abstract Classes____________.pptx
05-OOP-Abstract Classes____________.pptx05-OOP-Abstract Classes____________.pptx
05-OOP-Abstract Classes____________.pptx
paautomation11
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdf
arishmarketing21
 
Applying Real-time SQL Changes in your Hazelcast Data Grid
Applying Real-time SQL Changes in your Hazelcast Data GridApplying Real-time SQL Changes in your Hazelcast Data Grid
Applying Real-time SQL Changes in your Hazelcast Data Grid
Hazelcast
 
HELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdfHELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdf
fatoryoutlets
 

Similar to Advance GORM (20)

Grails domain
Grails domainGrails domain
Grails domain
 
Gorm
GormGorm
Gorm
 
Gorm
GormGorm
Gorm
 
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)
 
GORM
GORMGORM
GORM
 
GORM
GORMGORM
GORM
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Grails basics part2
Grails basics  part2Grails basics  part2
Grails basics part2
 
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
 
XQuery Triggers in Native XML Database Sedna
XQuery Triggers in Native XML Database SednaXQuery Triggers in Native XML Database Sedna
XQuery Triggers in Native XML Database Sedna
 
Elastic tire demo
Elastic tire demoElastic tire demo
Elastic tire demo
 
05-OOP-Abstract Classes____________.pptx
05-OOP-Abstract Classes____________.pptx05-OOP-Abstract Classes____________.pptx
05-OOP-Abstract Classes____________.pptx
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdf
 
Applying Real-time SQL Changes in your Hazelcast Data Grid
Applying Real-time SQL Changes in your Hazelcast Data GridApplying Real-time SQL Changes in your Hazelcast Data Grid
Applying Real-time SQL Changes in your Hazelcast Data Grid
 
Day 2
Day 2Day 2
Day 2
 
HELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdfHELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdf
 

More from NexThoughts Technologies

Alexa skill
Alexa skillAlexa skill
GraalVM
GraalVMGraalVM
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
NexThoughts Technologies
 
Apache commons
Apache commonsApache commons
Apache commons
NexThoughts Technologies
 
HazelCast
HazelCastHazelCast
MySQL Pro
MySQL ProMySQL Pro
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
NexThoughts Technologies
 
Swagger
SwaggerSwagger
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
NexThoughts Technologies
 
Arango DB
Arango DBArango DB
Jython
JythonJython
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
NexThoughts Technologies
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
NexThoughts Technologies
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
NexThoughts Technologies
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
NexThoughts Technologies
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
NexThoughts Technologies
 
Ethereum
EthereumEthereum
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
NexThoughts Technologies
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
NexThoughts Technologies
 
Google authentication
Google authenticationGoogle authentication
Google authentication
NexThoughts Technologies
 

More from NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 

Recently uploaded

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 

Recently uploaded (20)

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 

Advance GORM

  • 2. Topics ● Events and Auto Timestamping ● Custom ORM mapping ● Default Sort Order ● Validations and Constraints
  • 3. Events and Auto Timestamping 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.
  • 4. Example - The beforeInsert event Fired before an object is saved to the database class Person { private static final Date NULL_DATE = new Date(0) String firstName String lastName Date signupDate = NULL_DATE def beforeInsert() { if (signupDate == NULL_DATE) { signupDate = new Date() } } }
  • 5. 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. class Person { Date dateCreated Date lastUpdated }
  • 6. Custom ORM mapping Custom mappings are defined using a static mapping block defined within your domain class: class Person { … static mapping = { version false autoTimestamp false } } You can also configure global mappings in application.groovy (or an external config file) using this setting: grails.gorm.default.mapping = { version false autoTimestamp false }
  • 7. Table and Column Names Table names The database table name which the class maps to can be customized using the table method: class Person { ... static mapping = { table 'people' } } In this case the class would be mapped to a table called people instead of the default name of person.
  • 8. Column names It is also possible to customize the mapping for individual columns onto the database. For example to change the name you can do: class Person { String firstName static mapping = { table 'people' firstName column: 'First_Name' } } Here firstName is a dynamic method within the mapping Closure that has a single Map parameter. Since its name corresponds to a domain class persistent field, the parameter values (in this case just "column") are used to configure the mapping for that property.
  • 9. Column type GORM supports configuration of Hibernate types with the DSL using the type attribute. This includes specifying user types that implement the Hibernate org.hibernate.usertype.UserType interface, which allows complete customization of how a type is persisted. class Address { String number String postCode static mapping = { postCode type: 'text' } }
  • 10. Many-to-One/One-to-One Mappings In the case of associations it is also possible to configure the foreign keys used to map associations. In the case of a many-to-one or one-to-one association this is exactly the same as any regular column. For example consider the following: class Person { String firstName Address address static mapping = { table 'people' firstName column: 'First_Name' address column: 'Person_Address_Id' } }
  • 11. One-to-Many Mapping class Person { static hasMany = [addresses: Address] static mapping = { addresses column: 'Person_Address_Id' } } If you don’t want the column to be in the address table, but instead some intermediate join table you can use the joinTable parameter: class Person { static hasMany = [addresses: Address] static mapping = { addresses joinTable: [name: 'Person_Addresses', key: 'Person_Id', column: 'Address_Id'] } }
  • 12. Many-to-Many Mapping GORM, by default maps a many-to-many association using a join table.To change the column names you can specify a column within the mappings for each class. class Group { ... static hasMany = [people: Person] static mapping = { people column: 'Group_Person_Id' } } class Person { ... static belongsTo = Group static hasMany = [groups: Group] static mapping = { groups column: 'Group_Group_Id' }
  • 13. Many-to-Many Mapping You can also specify the name of the join table to use: class Group { ... static mapping = { people column: 'Group_Person_Id', joinTable: 'PERSON_GROUP_ASSOCIATIONS' } } class Person { ... static mapping = { groups column: 'Group_Group_Id', joinTable: 'PERSON_GROUP_ASSOCIATIONS' } }
  • 14. Default Sort Order You can sort objects using query arguments such as those found in the list method: def airports = Airport.list(sort:'name') class Airport { ... static mapping = { sort "name" } } class Airport { ... static mapping = { sort name: "desc" } }
  • 15. Finally, you can configure sorting at the association level: class Airport { ... static hasMany = [flights: Flight] static mapping = { flights sort: 'number', order: 'desc' } } In this case, the flights collection will always be sorted in descending order of flight number.
  • 16. 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. 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) } } Validations
  • 17. Validating Constraints def user = new User(params) if(user.validate()){ //do something } else { user.errors.allErrors.each{ Println it } }
  • 18. Custom Validators class Response { Survey survey Answer answer static constraints = { survey blank: false answer blank: false, validator: { val, Response obj -> val in obj.survey.answers } } } The obj argument to the custom validator is the domain instance that is being validated, so we can access its survey property and return a boolean to indicate whether the new value for the answer property, val, is valid.