0

在 grails 应用程序中,我有一个默认为惰性的关系:

class Author{
    String name
    static mapping = {
         books lazy:false
    }
}

我有一个获取作者的标准 API 查询。当我运行查询

Author.createCriteria().list{
    eq("name", "John")
}

我为每个作者有 N+1 个子选择。

我的第二种方法是像这样急切地取书:

Author.createCriteria().list{
    eq("name", "John")
    fetchMode("books", FetchMode.JOIN)
}

在这种情况下,不会出现 N+1 选择问题,但是我有一个 JOIN 查询。

哪种方法在性能和优化方面更好?

4

1 回答 1

0

我认为您的意思是默认情况下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

如果您没有这样的(博客案例)案例,那么我将使用上面引用的示例进行优化性能

于 2013-06-08T21:27:21.970 回答