Grails:从HQL到DetachedCriteria查询

时间:2012-01-20 14:11:49

标签: grails hql gorm 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或者相似的结果(但是可能......?)并且不添加从作者到书的关系(否则它会非常明显)

感谢

2 个答案:

答案 0 :(得分: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,那么这是相应的代码:


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();

答案 1 :(得分:1)

这可以通过标准或分离的Criteria以一些方式完成,但是使用常规GORM标准会更容易一些,因为它实现了createAllias命令,而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]