我认为您的意思是默认情况下eager
而不是问题lazy
的第一行。
记住要点
当条件查询中包含关联时,默认情况下会急切地获取它们。
在您的情况下,您不需要books lazy:false
.
在优化方面,我会保证以下方法:Author
class Author {
String name
static hasMany = [books: Book]
static mapping = {
//books lazy:false (DO NOT NEED)
}
}
class Book {
String bookName
//set belongsTo if you need bi-directional one-many
//books gets cascade deleted when author is deleted
//static belongsTo = [author: Author]
}
//Bootstrap
def author1 = new Author(name: "Dan Brown")
def book1 = new Book(bookName: "Da Vinci Code")
def book2 = new Book(bookName: "Angels And Demons")
def book3 = new Book(bookName: "Inferno")
[book1, book2, book3].each {author1.addToBooks(it)}
author1.save(flush: true, failOnError: true)
//Criteria
Author.createCriteria().list{
eq("name", "Dan Brown")
books{
//books are eagerly fetched by default using inner join. No need to specify FetchMode.
}
}
在性能方面,如果我有每个作者都写了 20000 个博客(用博客代替书籍),我不会采用上述方法。急切地为作者获取 20000n
个博客将对性能造成影响。在这种情况下,我会选择惰性获取 (N + 1) 路由,并尝试根据我的要求过滤掉博客。如下所示:
def author = Author.findByName("Dan Brown")
def books = author.books
//Assume you have a field publishedYear in Book
def booksReleasedIn2013 = author.books.findAll{it.publishedYear == 2013}
def booksReleasedBefore2013 = author.books.findAll{it.publishedYear < 2013}
assert "Inferno" in booksReleasedIn2013*.bookName
assert "Angels And Demons" in booksReleasedBefore2013*.bookName
如果您没有这样的(博客案例)案例,那么我将使用上面引用的示例进行优化和性能。