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}" 

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
}

你可能感兴趣的:(grails)