`
sillycat
  • 浏览: 2552503 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Grails(5)Guide Book Chapter 6 GORM

 
阅读更多
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

分享到:
评论

相关推荐

    grails-datastore-gorm-plugin-support-2.0.4.RELEASE.zip

    《Grails Datastore GORM Plugin Support 2.0.4.RELEASE:开源项目的代码生成与Android MVC模式解析》 在IT行业中,开发高效且可维护的软件系统是至关重要的。Grails Datastore GORM Plugin Support 2.0.4.RELEASE...

    使用GORM构建Spring Boot应用程序 Grails指南_ Grails框架.pdf

    在本教程中,我们将探讨如何使用GORM(Grails Object-Relational Mapping)构建Spring Boot应用程序。GORM是Grails框架的核心部分,它为开发者提供了简单、强大的数据持久化功能,支持Hibernate和MongoDB等数据库。...

    the definitive guide to grails 2

    通过GORM(Grails Object Relational Mapping),Grails提供了自动的ORM支持,使得开发者无需编写复杂的SQL语句即可实现数据的持久化操作。 #### Controllers(控制器) 控制器(Controllers)负责处理来自用户的...

    grails-datastore-gorm-tck-1.0.9.RELEASE.zip

    标题 "grails-datastore-gorm-tck-1.0.9.RELEASE.zip" 提供的信息表明,这是一个与Grails框架相关的数据存储(Datastore)和GORM(Grails Object Relational Mapping)测试兼容性工具包(Test Compatibility Kit,...

    Grails GORM查询.pdf

    Grails框架中的GORM(Groovy Object Relational Mapping)是利用Groovy语言的优势来简化数据库操作的一套对象关系映射技术。GORM支持多种查询方式,提供了类似于Hibernate的查询能力,并且由于Groovy语言的动态特性...

    grails-data-mapping:GORM-Groovy对象映射

    GORM(Grails对象映射) [Grails] [Grails]是用于使用[Groovy] [Groovy]编程语言构建Web应用程序的框架。 该项目为Hibernate和NoSQL数据存储上的GORM的新实现提供了GORM API管道。 [Grails]: : [Groovy]: : ...

    The definitive guide to grails 2 英文版 书 代码

    5. **GORM(Grails Object Relational Mapping)**:解释GORM如何简化数据库操作,包括数据模型定义、查询语言GQL、关联映射等。 6. **Controllers与Views**:探讨控制器如何处理请求,以及视图如何渲染响应,包括...

    Grails Persistence with GORM and GSQL

    Grails Persistence with GORM and GSQL

    GORM的独立启动(Standalone)

    在IT行业中,GORM是一个非常重要的工具,尤其在Grails框架中,它是处理数据库操作的主要接口。本篇文章将深入探讨GORM的独立启动(Standalone)功能,这使得开发者可以在不依赖整个Grails应用的情况下使用GORM的强大...

    Grails Grails Grails

    5. **构建工具**:Grails 使用Gradle作为其构建工具,允许自定义构建流程和依赖管理。 **Grails1.1中文文档** 《Grails1.1中文文档》是Grails 1.1版本的官方中文指南,包含了框架的详细介绍、安装指南、基本概念、...

    grails 开发框架-5

    grails1.0开发框架5 类似于ruby on rails的框架。

    grails 中文文档+grails-fckeditor-0.9.5.zip插件

    2. MVC架构:Grails遵循Model-View-Controller(MVC)设计模式,通过GORM(Grails Object Relational Mapping)进行数据访问,使用GSP(Groovy Server Pages)作为视图模板,Controller负责业务逻辑处理。...

    Grails权威指南 Grails权威指南

    6. **Grails构建工具**:Grails的构建系统自动化处理许多任务,如依赖管理、资源处理、测试执行等,使得开发流程更加顺畅。 7. **RESTful服务**:Grails支持创建RESTful API,这在当今的微服务架构中尤为重要。...

    The definate guide to Grails

    - **域类(Domain Classes)**:Grails 的域类用于表示应用程序中的数据模型,它们自动继承自 grails.datastore.gorm.api.Persistent 类,从而获得了数据持久化的能力。 - **控制器(Controllers)**:Grails 控制器...

    使用 Grails 快速开发 Web 应用程序

    Grails的自动化工具如GORM(Grails Object-Relational Mapping)将帮助快速生成数据库操作的代码。 通过本教程,读者将掌握Grails的基本开发技术,包括Groovy语言基础、MVC模式的理解以及Grails框架的核心组件使用...

    The definitive guide to grails_2 源代码

    《The Definitive Guide to Grails 2》是关于Grails框架的一本权威指南,它为读者提供了深入理解和使用Grails 2开发Web应用程序所需的知识。Grails是一种基于Groovy语言的开源全栈式Web应用框架,它借鉴了Ruby on ...

Global site tag (gtag.js) - Google Analytics