Grails 技巧 - GORM篇

1.不生成 version 字段

static mapping = {
    version false
}

2.分页结果集列表 PagedResultList,非常适合分页查询

def c = Account.createCriteria()
def results = c.list (max: 50, offset: 10) {
    like("holderFirstName", "Fred%")
    and {
        between("balance", 500, 1000)
        eq("branch", "London")
    }
    order("holderLastName", "desc")
}
println "Rendering ${results.size()} Accounts of ${results.totalCount}" 

results.size() 为返回的 list 记录大小,上面为offset为10的50条记录

results.totalCount 为符合条件记录在数据库大小

3.使用proxy() 方法获取关联Domain

class Book{
    Author author 
}

def author=Author.proxy(1)  //不会到数据去查询实际数据

Book.findByAuthor(author)

author只是补助作用,不需要实际数据,如果用get方法效率低下

用proxy 方法实际没有连接数据库

4.便捷方法

  • findOrCreate
  • getAll
  • read
  • first
  • last

5.Domain 数据非常大,不希望直接关联,可以采用间接关联

class Book{

  static transients = ['author']
  
  Long authorId

  Author getAuthor(){
        Author.get(authorId)
  }

   void setAuthor(Author author){
        authorId=author.id   
   }

}

6.SQL Restrictions

def c = Person.createCriteria()
def peopleWithShortFirstNames = c.list {
    sqlRestriction "char_length(first_name) <= 4"
}

7.Query cache

修改 DataSource.groovy 使 cache.use_query_cache=true

hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class='org.hibernate.cache.EhCacheProvider'
}

使用 Query cache

def person = Person.findByFirstName("Fred", [cache: true])

def people = Person.withCriteria {
    like('firstName', 'Fr%')
    cache true
}

8.Where Queries

Grails 2.0 新增的简洁强大查询方式

def query = Person.where {
   firstName == "Bart"
}
Person bart = query.find()


class Person {
    static simpsons = where {
         lastName == "Simpson"
    }
    …
}
…
Person.simpsons.each {
    println it.firstname
}

9.Batch Updates and Deletes

def query = Person.where {
    lastName == 'Simpson'
}
int total = query.updateAll(lastName:"Bloggs")

def query = Person.where {
    lastName == 'Simpson'
}
int total = query.deleteAll()

10.Inheritance Strategies

默认是 table-per-hierarchy (每个层级 一个表) 策略

如果希望table-per-subclass(每个子类一个表) 策略 使用 tablePerHierarchy false

class Payment {
    Integer amount
    static mapping = {
        tablePerHierarchy false
    }
}

class CreditCardPayment extends Payment {
    String cardNumber
}

转载于:https://my.oschina.net/linghuchong/blog/137974

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值