Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Persistence Basic
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()
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 Content { class BlogEntry extends Content { class Book extends Content {
String author URL url String ISBN
} } }
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 def airport = Airport.findByName("Gatwick")
for (flight in airport.flights) {
static hasMany = [flights: Flight] println flight.destination.city
} }
class Flight { GORM will execute a single SQL query to fetch the Airport
String number
instance, another to get its flights, and then 1 extra query
Location destination
static belongsTo = [airport: Airport] 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).
class Location {
String city
String country
}
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