Grails(5)Guide Book Chapter 6 GORM
6.3 Persistence Basics
6.3.1 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.
try{
p.save(flush: true) //Flush immediately.
}catch(org.springframework.dao.DataIntegrityViolationException e){
}
Grails validates a domain instance every time when we save it.
try{
p.save(failOnError: true)
}catch{}
6.3.2 Deleting Objects
def p = Person.get(1)
p.delete()
Almost the save as during saving
try{
p.delete(flush:true)
}catch(org.springframework.dao.DataIntegrityViolationException e){}
If we need batch deleting function, we use executeUpdate
Customer.executeUpdate("delete Customer c where c.name =
ldName",
[oldName: "Carl"])
6.3.3 Understanding Cascading Updates and Deletes
6.3.4 Eager and Lazy Fetching
Default are lazy fetching
Configuring Eager Fetching
class Airport {
String name
static hasMany = [flights: Flight]
static mapping = {
flights lazy: false
}
}
Using Batch Fetching
If we use eager fetch all the time for all the data, it will result some performance and memory problems.
class Airport {
String name
static hasMany = [flights: Flight]
static mapping = {
flights batchSize: 10
}
}
Or
class Flight {
…
static mapping = {
batchSize 10
}
}
6.3.5 Pessimistic and Optimistic Locking
def airport = Airport.lock(10)
6.3.6 Modification Checking
isDirty
We can use this method to check if any field has been modified.
def airport = Airport.get(10)
assert !airport.isDirty()
airport.properties = params
if(airport.isDirty()) {
...
}
We can also check if individual fields have been modified.
def airport = Airport.get(10)
assert !airport.isDirty()
airport.properties = params
if(airport.isDirty('name')){
…snip...
}
getDirtyPropertyNames
We can use this method to retrieve the names of modified fields.
def airport = Airport.get(10)
assert !airport.isDirty()
airport.properties = params
def modifiedFieldNames = airport.getDirtyPropertyNames()
for(fieldName in modifiedFieldNames){
…snip...
}
getPersistentValue
We can also use this 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){
…snip...
}
}
6.4 Querying with GORM
Dynamic Finders
Where Queries
Criteria Queries
Hibernate Query Language(HQL)
Listing Instances
def books = Book.list()
def books = Book.list(offset:10, max: 20) //pagination
def books = Book.list(sort:"title", order:"asc") //sort
Retrieval by Database Identifier
def book = Book.get(23)
def books = Book.getAll(23,93,81)
6.4.1 Dynamic Finders
class Book {
String title
Date releaseDate
Author author
}
class Author {
String name
}
def book = Book.findByTitle("The Python")
book = Book.findByTitleLike("Python%")
book = Book.findByReleaseDateBetween(firstDate, secondDate)
book = Book.findByReleaseDateGreaterThan(someDate)
book = Book.findByTitleLikeOrReleaseDateLessThan("%Python%", someDate)
Method Expressions
InList, LessThan, LessThanEquals, GreaterThan, GreaterThanEquals
Like,
Ilike - similar to Like, except case insensitive
NotEqual, Between, IsNotNull, IsNull
Boolean logic (AND/OR)
def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan(
“%Java%”, new Date() -30)
Querying Associations
Pagination and Sorting
6.4.2 Where Queries
Basic Querying
def query = Person.where {
firstName == "Carl"
}
Person carl = query.find()
Person p = Person.find { firstName == "Carl" }
def results = Person.findAll {
lastName == "Luo"
}
== eq
!= ne
> gt
< lt
>= ge
<= le
in inList
==~ like
=~ ilike
def query = Person.where {
(lastName != "Carl" && firstName != "Book") || (firstName == "Carl" && age > 9)
}
def results = query.list(sort:"firstName")
Query Composition
Conjunction, Disjunction and Negation
…snip…
6.4.3 Criteria
6.4.4 Detached Criteria
6.4.5 Hibernate Query Language(HQL)
def results =
Book.findAll("from Book as b where b.title like 'Lord of the%'")
Positional and Named Parameters
def results =
Book.findAll("from Book as b where b.title like ?", ["The Shi%"])
Or named parameters
def books = Book.findAll("from Book as book where book.author = :author",
[author:author])
Pagination and Sorting
def results =
Book.findAll("from Book as b where " +
"b.title like 'Lord of the%' " +
"order by b.title sac",
[max: 10, offset: 20])
6.5 Advanced GORM Features
6.5.1 Events and Auto Timestamping
Event Types
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()
}
}
}
The beforeUpdate event
Fired before an existing object is updated
class Person {
def securityService
String firstName
String lastName
String lastUpdateBy
static constraints = {
lastUpdatedBy nullable: true
}
def beforeUpdate() {
lastUpdateBy = securityService.currentAuthenticatedUsername()
}
}
The beforeDelete event
Fired before an object is deleted.
class Person {
String name
def beforeDelete() {
ActivityTrace.withNewSession {
new ActivityTrace(eventName: "Person Deleted", data: name).save()
}
}
}
The beforeValidate event
Fired before an object is validated.
class Person {
String name
static constraints = {
name size: 5..45
}
def beforeValidate(){
name = name?.trim()
}
}
The onLoad/beforeLoad event
class Person {
String name
Date dateCreated
Date lastUpdated
def onLoad() {
log.debug "Loading ${id}"
}
}
The afterLoad event
Fired immediately after an object is loaded from the database:
class Person {
String name
Date dateCreated
Date lastUpdated
def afterLoad() {
name = "I'm loaded"
}
}
Custom Event Listeners
6.5.2 Custom ORM Mapping
6.5.2.1 Table and Column Names
6.5.2.2 Caching Strategy
Setting up caching
configured in the grails-app/conf/DateSource.groovy
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.provider_class = 'org.hibernate.cache.EhCacheProvider'
}
6.5.2.3 Inheritance Strategies
6.5.2.4 Custom Database Identity
6.5.2.9 Custom Cascade Behaviour
…snip...
References:
http://grails.org/doc/latest/guide/GORM.html#persistenceBasics
http://grails.org/doc/latest/guide/index.html