Author{
String name;
List<Book> books
static hasMany= [books: Book]
}
Book{
int number_of_pages;
String name;
}
我想查询并获取按排序的特定作者的前 10 本书number_of_pages
Author{
String name;
List<Book> books
static hasMany= [books: Book]
}
Book{
int number_of_pages;
String name;
}
我想查询并获取按排序的特定作者的前 10 本书number_of_pages
使用 HQL,您可以:
def query = "select book from Author author join author.books book where author=:author order by book.number_of_pages"
def books = Author.executeQuery(query, [author: author], [max: 10])
注意:您应该重命名number_of_pages
为numberOfPages
.
我建议您通过将作者添加为 Book 的属性,使 Author 对 Book 可见。
这样你可以这样做:
Book.findAll(sort: 'number_of_pages', max: 10) { author.id == myAuthorVariable.id }
虽然,有更好的方法。如果你让 Author 实现 equals 方法,你可以这样写:
Book.findAll(sort: 'number_of_pages', max: 10) { author == myAuthorVariable }
此外,您可以设置“偏移量”,即从 x 寄存器开始给我带来 10 本书。这对于分页很有用:
Book.findAll(sort: 'number_of_pages', max: 10, offset: 50) { author == myAuthorVariable }
Author 的 equals 实现可以是:
def boolean equals(author) {
if (this.is(author)) return true
if (!author || getClass() != author.class) return false
return this.name == author.name
}