SlideShare une entreprise Scribd logo
1  sur  30
GORM
(Object Relational Mapping)
Object Relational Mapping(GORM)
GORM is Grails' object relational mapping (ORM) implementation.
Under the hood it uses Hibernate 3 and less configuration involved
in creating Grails domain classes.
Agenda
Let's Start
Domain Modelling in GORM
Persistence Basic
Querying with GORM
GORM and Constraints
Let's Start
A domain class can be created with the create-domain-class command:
grails create-domain-class helloworld.Person
This will create a class at the location grails-app/domain/helloworld/Person.groovy such as the
one below:
package helloworld
class Person {
}
Basic Oprations
Basic operations also know as CRUD:
1)Create
2)Read
3)Update
4)Delete
Create
Person p = new Person()
p.name = “Vijay”
p.age = 25
p.lastVisit = new Date()
p.save()
Person p = new Person(name: "Fred", age: 40, lastVisit: new Date())
p.save()
Read/Retrieve
get(), read(), load()
get():- Retrieves an instance of the domain class for the specified id.
read():- Retrieves an instance of the domain class for the specified id in a read-only state.
load():- Returns a proxy instance of the domain class for the given identifier.
Ex:- def p = Person.get(1)
assert 1 = p.id
Note*:- In case of get() and read() null is returned if the row with the specified id doesn't exist.
get() vs read() vs load()
get() vs read()
The read method is similar to the get method except that automatic dirty detection(check all the
properties) is disabled.
The instance isn't truly read-only - you can modify it - but if it isn't explicitly saved but has been modified, it
won't be updated in the database during a flush.
get() vs load()
get() returns null if data is not found in session as well as database, but load() returns
ObjectNotFoundException().
get() always return completely initialized object while load() may be not.
Update
To update an instance, change some properties and then call save again:
def p = Person.get(1)
p.name = "Bob"
p.save()
Delete
To delete an instance use the delete method:
def p = Person.get(1)
p.delete()
Domain Modelling in Gorm
1.Association in GORM
a.Many-To-One/One-To-One
b.One-To-Many
c.Many-To-Many
2.Basic Collection Types
3.Composition in GORM
4.Inheritance in GORM
5.Sets, List, Map
Many-To-One/One-To-One
Unidirectional Bidirectional
class Face {
Nose nose
}
class Nose {
}
class Face {
Nose nose
}
class Nose {
static belongsTo = [face:Face]
}
One-To-many
A one-to-many relationship is when one class, has many instances of another class. With
Grails you define such a relationship with the hasMany setting:
class Author {
static hasMany = [books: Book]
String name
}
class Book {
String title
}
The default cascading behaviour is to cascade saves and updates, but not deletes unless a belongsTo is
also specified:
class Author {
static hasMany = [books: Book]
String name
}
class Book {
static belongsTo = [author: Author]
String title
}
Many-to-many
Grails supports many-to-many relationships by defining a hasMany on both sides of the relationship and
having a belongsTo on the owned side of the relationship:
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
String title
}
class Author {
static hasMany = [books:Book]
String name
}
Composition in gorm
Grails supports the notion of composition. In this case instead of mapping classes onto separate tables a
class can be "embedded" within the current table.
class Person {
Address homeAddress
Address workAddress
static embedded = ['homeAddress', 'workAddress']
}
class Address {
String number
String code
}
Inheritance in gorm
GORM supports inheritance both from abstract base classes and concrete persistent GORM entities.
class Content {
String author
}
class BlogEntry extends Content {
URL url
}
class Book extends Content {
String ISBN
}
def content = Content.list() // list all blog entries and books
content = Content.findAllByAuthor('Joe Bloggs') // find all by author
Persistence Basic
Saving and Updating
Deleting Objects
Cascading Updates and Delete
Eager and Lazy Fetching
Pessimistic and Optimistic Lock
Modification Checking
Persistence Basics
A key thing to remember about Grails is that under the surface Grails is using
Hibernate for persistence.
Grails automatically binds a Hibernate session to the currently executing request.
This lets you use the save and delete methods as well as other GORM methods
transparently.
Saving and Updating
def p = Person.get(1)
p.save()
This save will be not be pushed to the database immediately - it will be pushed when the
next flush occurs.
But there are occasions when you want to control when those statements are executed or, in
Hibernate terminology, when the session is "flushed". To do so you can use the flush
argument to the save method:
def p = Person.get(1)
p.save(flush: true)
Another thing to bear in mind is that Grails validates a domain instance every time
you save it. If that validation fails the domain instance will not be persisted to the
database. By default, save() will simply return null in this case, but if you would
prefer it to throw an exception you can use the failOnError argument:
def p = Person.get(1)
try {
p.save(failOnError: true)
}
catch (ValidationException e) {
// deal with exception
}
Eager and lazy fetching
class Airport {
String name
static hasMany = [flights: Flight]
}
class Flight {
String number
Location destination
static belongsTo = [airport: Airport]
}
class Location {
String city
String country
}
def airport = Airport.findByName("Gatwick")
for (flight in airport.flights) {
println flight.destination.city
}
GORM will execute a single SQL query to fetch the Airport
instance, another to get its flights, and then 1 extra query
for each iteration over the flights association to get the
current flight's destination. In other words you get N+1
queries (if you exclude the original one to get the airport).
Configuring eager fetching
class Airport {
String name
static hasMany = [flights: Flight]
static mapping = {
flights lazy: false
}
}
Modification checking
isDirty:- You can use the isDirty method to check if any field has been modified:
getDirtyPropertyNames:- You can use the getDirtyPropertyNames method to retrieve the names of
modified fields; this may be empty but will not be null.
getPersistentValue:- You can use the getPersistentValue method to retrieve the value of a modified field
def airport = Airport.get(10)
assert !airport.isDirty()
airport.properties = params
def modifiedFieldNames = airport.getDirtyPropertyNames()
for (fieldName in modifiedFieldNames) {
def currentValue = airport."$fieldName"
def originalValue = airport.getPersistentValue(fieldName)
if (currentValue != originalValue) {
// do something based on changed value
}
}
Querying with GORM
Dynamic Finder
Where Queries
Criteria
Detached Criteria
HQL
Advanced gorm features
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.
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 Columns name
class Person {
…
static mapping = {
table 'people'
}
}
class Person {
String firstName
static mapping = {
table 'people'
firstName column: 'First_Name'
}
}
class Address {
String number
String postCode
static mapping = {
postCode type: PostCodeType
}
}
GORM and Constraints
https://grails.github.io/grails-doc/3.0.x/guide/GORM.html#basicCollectionTypes
Reference
https://grails.github.io/grails-doc/3.0.x/guide/GORM.html

Contenu connexe

Tendances

The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210Mahmoud Samir Fayed
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwoEishay Smith
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your GroovyAlonso Torres
 
Power shell object
Power shell objectPower shell object
Power shell objectLearningTech
 
Introduction to Gremlin
Introduction to GremlinIntroduction to Gremlin
Introduction to GremlinMax De Marzi
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickHermann Hueck
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceSeung-Bum Lee
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Json and SQL DB serialization Introduction with Play! and Slick
Json and SQL DB serialization Introduction with Play! and SlickJson and SQL DB serialization Introduction with Play! and Slick
Json and SQL DB serialization Introduction with Play! and SlickStephen Kemmerling
 
Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...
Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...
Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...ICS User Group
 
Using Regular Expressions and Staying Sane
Using Regular Expressions and Staying SaneUsing Regular Expressions and Staying Sane
Using Regular Expressions and Staying SaneCarl Brown
 
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180Mahmoud Samir Fayed
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arraysHassan Dar
 
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...CloudxLab
 
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQLPGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQLPGConf APAC
 
Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansCarol McDonald
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31Mahmoud Samir Fayed
 

Tendances (20)

The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
Power shell object
Power shell objectPower shell object
Power shell object
 
Introduction to Gremlin
Introduction to GremlinIntroduction to Gremlin
Introduction to Gremlin
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Json and SQL DB serialization Introduction with Play! and Slick
Json and SQL DB serialization Introduction with Play! and SlickJson and SQL DB serialization Introduction with Play! and Slick
Json and SQL DB serialization Introduction with Play! and Slick
 
Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...
Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...
Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...
 
Using Regular Expressions and Staying Sane
Using Regular Expressions and Staying SaneUsing Regular Expressions and Staying Sane
Using Regular Expressions and Staying Sane
 
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
groovy & grails - lecture 3
groovy & grails - lecture 3groovy & grails - lecture 3
groovy & grails - lecture 3
 
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
 
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQLPGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
 
Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with Netbeans
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31
 

Similaire à Gorm

Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: MinneapolisGroovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: MinneapolisJenn Strater
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Groovy Api Tutorial
Groovy Api  TutorialGroovy Api  Tutorial
Groovy Api Tutorialguligala
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suckRoss Bruniges
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript PrimerAdam Hepton
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Codestasimus
 
Grails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitGrails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitZachary Klein
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
Inside Gorm
Inside GormInside Gorm
Inside Gormkrimple
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 

Similaire à Gorm (20)

Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: MinneapolisGroovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Advance GORM
Advance GORMAdvance GORM
Advance GORM
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Groovy Api Tutorial
Groovy Api  TutorialGroovy Api  Tutorial
Groovy Api Tutorial
 
groovy & grails - lecture 11
groovy & grails - lecture 11groovy & grails - lecture 11
groovy & grails - lecture 11
 
Clean Code
Clean CodeClean Code
Clean Code
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript Primer
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
 
Grails domain
Grails domainGrails domain
Grails domain
 
Grails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitGrails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to Orbit
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Inside Gorm
Inside GormInside Gorm
Inside Gorm
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 

Plus de 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
 

Dernier

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 

Dernier (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Gorm

  • 2. Object Relational Mapping(GORM) GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 and less configuration involved in creating Grails domain classes.
  • 3. Agenda Let's Start Domain Modelling in GORM Persistence Basic Querying with GORM GORM and Constraints
  • 4. Let's Start A domain class can be created with the create-domain-class command: grails create-domain-class helloworld.Person This will create a class at the location grails-app/domain/helloworld/Person.groovy such as the one below: package helloworld class Person { }
  • 5. Basic Oprations Basic operations also know as CRUD: 1)Create 2)Read 3)Update 4)Delete
  • 6. Create Person p = new Person() p.name = “Vijay” p.age = 25 p.lastVisit = new Date() p.save() Person p = new Person(name: "Fred", age: 40, lastVisit: new Date()) p.save()
  • 7. Read/Retrieve get(), read(), load() get():- Retrieves an instance of the domain class for the specified id. read():- Retrieves an instance of the domain class for the specified id in a read-only state. load():- Returns a proxy instance of the domain class for the given identifier. Ex:- def p = Person.get(1) assert 1 = p.id Note*:- In case of get() and read() null is returned if the row with the specified id doesn't exist.
  • 8. get() vs read() vs load() get() vs read() The read method is similar to the get method except that automatic dirty detection(check all the properties) is disabled. The instance isn't truly read-only - you can modify it - but if it isn't explicitly saved but has been modified, it won't be updated in the database during a flush. get() vs load() get() returns null if data is not found in session as well as database, but load() returns ObjectNotFoundException(). get() always return completely initialized object while load() may be not.
  • 9. Update To update an instance, change some properties and then call save again: def p = Person.get(1) p.name = "Bob" p.save()
  • 10. Delete To delete an instance use the delete method: def p = Person.get(1) p.delete()
  • 11. Domain Modelling in Gorm 1.Association in GORM a.Many-To-One/One-To-One b.One-To-Many c.Many-To-Many 2.Basic Collection Types 3.Composition in GORM 4.Inheritance in GORM 5.Sets, List, Map
  • 12. Many-To-One/One-To-One Unidirectional Bidirectional class Face { Nose nose } class Nose { } class Face { Nose nose } class Nose { static belongsTo = [face:Face] }
  • 13. One-To-many A one-to-many relationship is when one class, has many instances of another class. With Grails you define such a relationship with the hasMany setting: class Author { static hasMany = [books: Book] String name } class Book { String title }
  • 14. The default cascading behaviour is to cascade saves and updates, but not deletes unless a belongsTo is also specified: class Author { static hasMany = [books: Book] String name } class Book { static belongsTo = [author: Author] String title }
  • 15. Many-to-many Grails supports many-to-many relationships by defining a hasMany on both sides of the relationship and having a belongsTo on the owned side of the relationship: class Book { static belongsTo = Author static hasMany = [authors:Author] String title } class Author { static hasMany = [books:Book] String name }
  • 16. Composition in gorm Grails supports the notion of composition. In this case instead of mapping classes onto separate tables a class can be "embedded" within the current table. class Person { Address homeAddress Address workAddress static embedded = ['homeAddress', 'workAddress'] } class Address { String number String code }
  • 17. Inheritance in gorm GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. class Content { String author } class BlogEntry extends Content { URL url } class Book extends Content { String ISBN } def content = Content.list() // list all blog entries and books content = Content.findAllByAuthor('Joe Bloggs') // find all by author
  • 18. Persistence Basic Saving and Updating Deleting Objects Cascading Updates and Delete Eager and Lazy Fetching Pessimistic and Optimistic Lock Modification Checking
  • 19. Persistence Basics A key thing to remember about Grails is that under the surface Grails is using Hibernate for persistence. Grails automatically binds a Hibernate session to the currently executing request. This lets you use the save and delete methods as well as other GORM methods transparently.
  • 20. Saving and Updating def p = Person.get(1) p.save() This save will be not be pushed to the database immediately - it will be pushed when the next flush occurs. But there are occasions when you want to control when those statements are executed or, in Hibernate terminology, when the session is "flushed". To do so you can use the flush argument to the save method: def p = Person.get(1) p.save(flush: true)
  • 21. Another thing to bear in mind is that Grails validates a domain instance every time you save it. If that validation fails the domain instance will not be persisted to the database. By default, save() will simply return null in this case, but if you would prefer it to throw an exception you can use the failOnError argument: def p = Person.get(1) try { p.save(failOnError: true) } catch (ValidationException e) { // deal with exception }
  • 22. Eager and lazy fetching class Airport { String name static hasMany = [flights: Flight] } class Flight { String number Location destination static belongsTo = [airport: Airport] } class Location { String city String country } def airport = Airport.findByName("Gatwick") for (flight in airport.flights) { println flight.destination.city } GORM will execute a single SQL query to fetch the Airport instance, another to get its flights, and then 1 extra query for each iteration over the flights association to get the current flight's destination. In other words you get N+1 queries (if you exclude the original one to get the airport).
  • 23. Configuring eager fetching class Airport { String name static hasMany = [flights: Flight] static mapping = { flights lazy: false } }
  • 24. Modification checking isDirty:- You can use the isDirty method to check if any field has been modified: getDirtyPropertyNames:- You can use the getDirtyPropertyNames method to retrieve the names of modified fields; this may be empty but will not be null. getPersistentValue:- You can use the getPersistentValue method to retrieve the value of a modified field def airport = Airport.get(10) assert !airport.isDirty() airport.properties = params def modifiedFieldNames = airport.getDirtyPropertyNames() for (fieldName in modifiedFieldNames) { def currentValue = airport."$fieldName" def originalValue = airport.getPersistentValue(fieldName) if (currentValue != originalValue) { // do something based on changed value } }
  • 25. Querying with GORM Dynamic Finder Where Queries Criteria Detached Criteria HQL
  • 26. Advanced gorm features 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.
  • 27. 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 }
  • 28. Table and Columns name class Person { … static mapping = { table 'people' } } class Person { String firstName static mapping = { table 'people' firstName column: 'First_Name' } } class Address { String number String postCode static mapping = { postCode type: PostCodeType } }