- 浏览: 2489744 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
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
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
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 433NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 297Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 379Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 338Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 419NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 365Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 294Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 213GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 395GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 279GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 267Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 267Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 255Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 240Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 238NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 229Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 520NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 232Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 324Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 323Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
使用GORM构建Spring Boot应用程序 Grails指南_ Grails框架.pdf
GORM(Grails对象映射) [Grails] [Grails]是用于使用[Groovy] [Groovy]编程语言构建Web应用程序的框架。 该项目为Hibernate和NoSQL数据存储上的GORM的新实现提供了GORM API管道。 [Grails]: : [Groovy]: : ...
简单介绍grails的查询操作,已经类似与hibnatate的查询方式
Grails Persistence with GORM and GSQL
详细介绍grails框架的奥秘,英文版你值得拥有
prestige.zip,android的mvc模式,android的代码生成驱动的mvc模式。
The definitive guide to grails 2 英文版 书和随书代码, 学习grails必备
grails1.0开发框架5 类似于ruby on rails的框架。
Grails Grails Grails Grails Grails
mobile-detect.zip,用于检测移动设备的轻量级Java库。用于检测移动设备的轻量级Java库。
In Grails: A Quick-Start Guide, you’ll see how to use Grails by iteratively building an unique, working application. By the time we’re done, you’ll have built and deployed a real, functioning ...
去年早些时候写的一个项目驱动的grails入门教程。绝对原创。
the best of the best. written by one of core author of grails team. Highly recommended.
grails 中文文档+grails-fckeditor-0.9.5.zip插件
Definitive Guide to Grails
Grails权威指南Grails权威指南Grails权威指南Grails权威指南Grails权威指南Grails权威指南
4.1 简化的orm和grails对象关系映射(gorm) 4.2 gorm基础 4.3 设置属性可选 4.4 gorm中的关系 4.5 执行crud操作 4.5.1 创建书签 4.5.2 读取书签 4.5.3 更新书签 4.5.4 ...