2012-01-20 44 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]