Grailsテクニック-GORM編

2779 ワード

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(階層ごとに1つのテーブル)ポリシーです.
    table-per-subclass(サブクラスごとに1つのテーブル)ポリシーを使用する場合は`tablePerHierarchy false`
    class Payment {
        Integer amount
        static mapping = {
            tablePerHierarchy false
        }
    }
    
    class CreditCardPayment extends Payment {
        String cardNumber
    }