SlideShare a Scribd company logo
Object Relational Mapping(GORM)
GORM is Grails' object relational mapping (ORM) implementation.
It uses Hibernate.
Agenda
Quick Start Guide
Domain Modelling in GORM
Persistence Basic
Querying with GORM
GORM and Constraints
Quick Start Guide
1.Basic Curd
a.Create
b.Update
c.Retrieve
d.Delete
grails create-domain-class helloworld.Person
class Person {
String name
Integer age
Date lastVisit
}
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
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.
get() loads the data as soon as it’s called whereas load() returns a proxy
object and loads data only when it’s actually required, so load() is better
because it support lazy loading.
Since load() throws exception when data is not found, we should use it only
when we know data exists.
We should use get() when we want to make sure data exists in the database.
Update
To update an instance, change some properties and then call save again:
def p = Person.get(1)
p.name = "Shukla"
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]
}
When we save or delete the Face instance, GORM will save or delete the Nose. In other words, saves
and deletes will cascade from Face to the associated Nose:-
new Face(nose:new Nose()).save()
Now if we delete the Face instance, the Nose will go too:
def f = Face.get(1)
f.delete() // both Face and Nose deleted
To make the relationship a true one-to-one, use the hasOne property on the owning side, e.g. Face:
Note that using this property puts the foreign key on the inverse table to the example A, so in this case the
foreign key column is stored in the nose table inside a column called face_id. Also, hasOne only works
with bidirectional relationships.
class Face {
static hasOne = [nose:Nose]
}
class Nose {
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:
In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.
Grails will automatically inject a property of type java.util.Set into the domain class based on the hasMany setting. This can
be used to iterate over the collection:-
class Author {
static hasMany = [books: Book]
String name
}
class Book {
String title
}
def a = Author.get(1)
for (book in a.books) {
println book.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:
Grails maps a many-to-many using a join table at the database level. The owning side of the relationship,
in this case Author, takes responsibility for persisting the relationship and is the only side that can cascade
saves across.
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, books and podcasts
content = Content.findAllByAuthor('Joe Bloggs') // find all by author
def podCasts = PodCast.list() // list only podcasts
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
}
}
Pessimistic and optimistic Lock
By default GORM classes are configured for optimistic locking. Optimistic locking is a feature of Hibernate
which involves storing a version value in a special version column in the database that is incremented
after each update.
When you perform updates Hibernate will automatically check the version property against the version
column in the database and if they differ will throw a StaleObjectException. This will roll back the
transaction if one is active.
This is useful as it allows a certain level of atomicity.
Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row
in the database. This has the implication that other read operations will be blocking until the lock is
released.
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
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

More Related Content

What's hot

11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
Miguel Silva Loureiro
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
Frayosh Wadia
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
Reem Alattas
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
nebuta
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
Adam Mukharil Bachtiar
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
Tugdual Grall
 
Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascading
johnynek
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startups
bmlever
 
Knolx session
Knolx sessionKnolx session
Knolx session
Knoldus Inc.
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越Caoyuan Deng
 
Interview C++11 code
Interview C++11 codeInterview C++11 code
Interview C++11 code
Russell Childs
 
Array and functions
Array and functionsArray and functions
Array and functions
Sun Technlogies
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
Hiromi Ishii
 
Apache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLabApache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLab
CloudxLab
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202
Mahmoud Samir Fayed
 

What's hot (20)

11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascading
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startups
 
Knolx session
Knolx sessionKnolx session
Knolx session
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
 
Interview C++11 code
Interview C++11 codeInterview C++11 code
Interview C++11 code
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
Array and functions
Array and functionsArray and functions
Array and functions
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
 
Apache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLabApache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLab
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202
 

Similar to Gorm

Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
Advance GORM
Advance GORMAdvance GORM
Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: MinneapolisGroovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
Jenn Strater
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Grailsでドメイン駆動設計を実践する時の勘所
Grailsでドメイン駆動設計を実践する時の勘所Grailsでドメイン駆動設計を実践する時の勘所
Grailsでドメイン駆動設計を実践する時の勘所
Takuma Watabiki
 
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
 
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
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
MongoDB
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
Amazon Web Services
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
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
 
Class loader basic
Class loader basicClass loader basic
Class loader basic명철 강
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorial
Dima Statz
 
CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
Christopher Bartling
 

Similar to Gorm (20)

Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Advance GORM
Advance GORMAdvance GORM
Advance GORM
 
Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: MinneapolisGroovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Grailsでドメイン駆動設計を実践する時の勘所
Grailsでドメイン駆動設計を実践する時の勘所Grailsでドメイン駆動設計を実践する時の勘所
Grailsでドメイン駆動設計を実践する時の勘所
 
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...
 
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
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
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...
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
 
Clean Code
Clean CodeClean Code
Clean Code
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorial
 
CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
 

More from Vijay Shukla

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

More from Vijay Shukla (19)

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

Recently uploaded

Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 

Recently uploaded (20)

Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 

Gorm

  • 1. Object Relational Mapping(GORM) GORM is Grails' object relational mapping (ORM) implementation. It uses Hibernate.
  • 2. Agenda Quick Start Guide Domain Modelling in GORM Persistence Basic Querying with GORM GORM and Constraints
  • 3. Quick Start Guide 1.Basic Curd a.Create b.Update c.Retrieve d.Delete grails create-domain-class helloworld.Person class Person { String name Integer age Date lastVisit }
  • 4. 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()
  • 5. 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
  • 6. 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.
  • 7. get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading. Since load() throws exception when data is not found, we should use it only when we know data exists. We should use get() when we want to make sure data exists in the database.
  • 8. Update To update an instance, change some properties and then call save again: def p = Person.get(1) p.name = "Shukla" p.save()
  • 9. Delete To delete an instance use the delete method: def p = Person.get(1) p.delete()
  • 10. 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
  • 11. Many-To-One/One-To-One Unidirectional Bidirectional class Face { Nose nose } class Nose { } class Face { Nose nose } class Nose { static belongsTo = [face:Face] }
  • 12. When we save or delete the Face instance, GORM will save or delete the Nose. In other words, saves and deletes will cascade from Face to the associated Nose:- new Face(nose:new Nose()).save() Now if we delete the Face instance, the Nose will go too: def f = Face.get(1) f.delete() // both Face and Nose deleted To make the relationship a true one-to-one, use the hasOne property on the owning side, e.g. Face: Note that using this property puts the foreign key on the inverse table to the example A, so in this case the foreign key column is stored in the nose table inside a column called face_id. Also, hasOne only works with bidirectional relationships. class Face { static hasOne = [nose:Nose] } class Nose { 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: In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table. Grails will automatically inject a property of type java.util.Set into the domain class based on the hasMany setting. This can be used to iterate over the collection:- class Author { static hasMany = [books: Book] String name } class Book { String title } def a = Author.get(1) for (book in a.books) { println book.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: Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case Author, takes responsibility for persisting the relationship and is the only side that can cascade saves across. 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, books and podcasts content = Content.findAllByAuthor('Joe Bloggs') // find all by author def podCasts = PodCast.list() // list only podcasts
  • 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. Pessimistic and optimistic Lock By default GORM classes are configured for optimistic locking. Optimistic locking is a feature of Hibernate which involves storing a version value in a special version column in the database that is incremented after each update. When you perform updates Hibernate will automatically check the version property against the version column in the database and if they differ will throw a StaleObjectException. This will roll back the transaction if one is active. This is useful as it allows a certain level of atomicity. Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in the database. This has the implication that other read operations will be blocking until the lock is released.
  • 25. 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 } }
  • 26. Querying with GORM Dynamic Finder Where Queries Criteria Detached Criteria HQL
  • 27. 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
  • 28. 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 }
  • 29. 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 }

Editor's Notes

  1. The ORM DSL allows mapping unidirectional relationships using a foreign key association instead The default fetch strategy used by Grails is "lazy", which means that the collection will be lazily initialized on first access. This can lead to the n+1 problem if you are not careful.
  2. If you define the Address class in a separate Groovy file in the grails-app/domain directory you will also get an address table. If you don't want this to happen use Groovy's ability to define multiple classes per file and include the Address class below the Person class in the grails-app/domain/Person.groovy file
  3. The version will only be updated after flushing the session.