SlideShare a Scribd company logo
1 of 19
Download to read offline
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 framesFAO
 
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, Samplingkrishna singh
 
3 R Tutorial Data Structure
3 R Tutorial Data Structure3 R Tutorial Data Structure
3 R Tutorial Data StructureSakthi 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: GORMSaurabh 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 spatialFAO
 
Creating a database
Creating a databaseCreating a database
Creating a databaseRahul Gupta
 
Sql queries - Basics
Sql queries - BasicsSql queries - Basics
Sql queries - BasicsPurvik Rana
 
Greenplum 6 Changes
Greenplum 6 ChangesGreenplum 6 Changes
Greenplum 6 ChangesVMware Tanzu
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply FunctionSakthi Dasans
 

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: 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
 
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.pdfaromanets
 
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 IEduardo Bergavera
 
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
 
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____________.pptxpaautomation11
 
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.pdfarishmarketing21
 
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 GridHazelcast
 
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.pdffatoryoutlets
 

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 (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

Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....rightmanforbloodline
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseWSO2
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaWSO2
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...SOFTTECHHUB
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 

Recently uploaded (20)

Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

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.