2012-01-20 45 views
1

讓說我有以下的域模型:的Grails:從HQL到的DetachedCriteria查詢

class Book { 
    String title 
    Set authors 

    static hasMany = {authors: Author} 
} 

class Author { 
    String name 
} 

的HQL查詢來獲取給定的標題圖書查詢作者的集合:

Author.executeQuery("select distinct author from Book as book join book.authors as author where book.name like ?", ["%groovy%"]) 

但我會能夠與DetachedCriteria或類似的(但它可能......?),並沒有增加從作者到書的關係相同的結果(否則它會很明顯)

ks

回答

1

不幸的是,AFAIK,這個查詢是不可能的。這可能與以下醜陋的查詢,但:


select author from Author author 
where author.id in (select author2.id from Book book 
        join book.authors as author2 
        where book.name like :bookName) 

對於這樣一個簡單的,非動態組成的查詢,我要和你HQL查詢堅持。如果你確實需要使用的標準,那麼這是對應的代碼:


Criteria c = session.createCriteria(Author.class, "author"); 
DetachedCriteria dc = DetachedCriteria.forClass(Book.class, "book"); 
dc.createAlias("book.authors", "author2"); 
dc.add(Restrictions.like("book.name", bookName)); 
dc.setProjection(Projections.property("author.id")); 
c.add(Subqueries.propertyIn("author.id", dc); 
List<Author> authors = (List<Author>) c.list(); 

+0

這些休眠的標準和查詢的DetachedCriteria?不是GORM標準和DetachedCriteria? 你有線索如何寫與德Grails/GORM標準和DetachedCriteria一樣嗎? –

+0

不,我認爲GORM只是Hibernate的Java API的封裝。 –

1

這是可以做到與標準或分離標準的一些方法,但因爲容易與普通格姆的標準有點它實現了createAlias吩咐的DetachedCriteria不一樣的Grails 2.2.2:

Create Alias In Detached Criteria

這裏有兩種方式:

package bookauthor 

import grails.gorm.DetachedCriteria 
import grails.orm.HibernateCriteriaBuilder 


class MyController { 

def index() { 
    HibernateCriteriaBuilder ac2 = Author.createCriteria() 
    HibernateCriteriaBuilder criteria2 = Author.createCriteria() 

    HibernateCriteriaBuilder criteria = Book.createCriteria() 

    def bookResults = criteria { 
    projections { 
     property 'aut.id' 
    } 
    createAlias('authors', 'aut') 
    like('title', '%Groovy%') 

    } 

    def dc = new DetachedCriteria(Book).build { 
    authors {} 
    like('title', '%Groovy%') 
    } 

    def myList = dc.list().collect { it.authors.collect { author -> author.id} }.flatten() 

    def resultsDetached = criteria2 { 
    'in'('id', myList) 
    } 

    def results = ac2 { 
    'in'('id', bookResults) 
    } 
log.info("RESULTS: " + results) 
log.info("Detached RESULTS: " + resultsDetached) 
} 

} 

您將在日誌中看到:

bookauthor.MyController - RESULTS: [bookauthor.Author : 1, bookauthor.Author : 3] 
bookauthor.MyController - Detached RESULTS: [bookauthor.Author : 1, bookauthor.Author : 3]