1

假设我有以下域模型:

class Book {
  String title
  Set authors

  static hasMany = {authors: Author}
}

class Author {
  String name
}

给定对书名的查询,检索 Author 集合的 HQL 查询:

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

但我将能够获得与 DetachedCriteria 或类似的结果相同的结果(但有可能......?)并且不添加从 Author 到 Book 的关系(否则它会很明显)

谢谢

4

2 回答 2

1

这可以通过标准或分离的标准通过几种方式完成,但使用常规的 GORM 标准会更容易一些,因为它实现了从 Grails 2.2.2 开始分离标准没有的 createAlias 命令:

在分离的条件中创建别名

以下是两种方式:

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]
于 2013-06-24T21:29:00.247 回答
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();

于 2012-01-20T14:28:53.960 回答