- 浏览: 2552503 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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 476NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 337Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 436Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 385Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 478NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 424Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 337Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 248GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 452GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 328GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 314Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 319Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 294Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 312Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 288NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 261Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 574NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 266Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 368Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 371Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
《Grails Datastore GORM Plugin Support 2.0.4.RELEASE:开源项目的代码生成与Android MVC模式解析》 在IT行业中,开发高效且可维护的软件系统是至关重要的。Grails Datastore GORM Plugin Support 2.0.4.RELEASE...
在本教程中,我们将探讨如何使用GORM(Grails Object-Relational Mapping)构建Spring Boot应用程序。GORM是Grails框架的核心部分,它为开发者提供了简单、强大的数据持久化功能,支持Hibernate和MongoDB等数据库。...
通过GORM(Grails Object Relational Mapping),Grails提供了自动的ORM支持,使得开发者无需编写复杂的SQL语句即可实现数据的持久化操作。 #### Controllers(控制器) 控制器(Controllers)负责处理来自用户的...
标题 "grails-datastore-gorm-tck-1.0.9.RELEASE.zip" 提供的信息表明,这是一个与Grails框架相关的数据存储(Datastore)和GORM(Grails Object Relational Mapping)测试兼容性工具包(Test Compatibility Kit,...
Grails框架中的GORM(Groovy Object Relational Mapping)是利用Groovy语言的优势来简化数据库操作的一套对象关系映射技术。GORM支持多种查询方式,提供了类似于Hibernate的查询能力,并且由于Groovy语言的动态特性...
GORM(Grails对象映射) [Grails] [Grails]是用于使用[Groovy] [Groovy]编程语言构建Web应用程序的框架。 该项目为Hibernate和NoSQL数据存储上的GORM的新实现提供了GORM API管道。 [Grails]: : [Groovy]: : ...
5. **GORM(Grails Object Relational Mapping)**:解释GORM如何简化数据库操作,包括数据模型定义、查询语言GQL、关联映射等。 6. **Controllers与Views**:探讨控制器如何处理请求,以及视图如何渲染响应,包括...
Grails Persistence with GORM and GSQL
在IT行业中,GORM是一个非常重要的工具,尤其在Grails框架中,它是处理数据库操作的主要接口。本篇文章将深入探讨GORM的独立启动(Standalone)功能,这使得开发者可以在不依赖整个Grails应用的情况下使用GORM的强大...
5. **构建工具**:Grails 使用Gradle作为其构建工具,允许自定义构建流程和依赖管理。 **Grails1.1中文文档** 《Grails1.1中文文档》是Grails 1.1版本的官方中文指南,包含了框架的详细介绍、安装指南、基本概念、...
grails1.0开发框架5 类似于ruby on rails的框架。
2. MVC架构:Grails遵循Model-View-Controller(MVC)设计模式,通过GORM(Grails Object Relational Mapping)进行数据访问,使用GSP(Groovy Server Pages)作为视图模板,Controller负责业务逻辑处理。...
6. **Grails构建工具**:Grails的构建系统自动化处理许多任务,如依赖管理、资源处理、测试执行等,使得开发流程更加顺畅。 7. **RESTful服务**:Grails支持创建RESTful API,这在当今的微服务架构中尤为重要。...
- **域类(Domain Classes)**:Grails 的域类用于表示应用程序中的数据模型,它们自动继承自 grails.datastore.gorm.api.Persistent 类,从而获得了数据持久化的能力。 - **控制器(Controllers)**:Grails 控制器...
Grails的自动化工具如GORM(Grails Object-Relational Mapping)将帮助快速生成数据库操作的代码。 通过本教程,读者将掌握Grails的基本开发技术,包括Groovy语言基础、MVC模式的理解以及Grails框架的核心组件使用...
《The Definitive Guide to Grails 2》是关于Grails框架的一本权威指南,它为读者提供了深入理解和使用Grails 2开发Web应用程序所需的知识。Grails是一种基于Groovy语言的开源全栈式Web应用框架,它借鉴了Ruby on ...