如何使用Grails从数据库加载hasMany实体

时间:2016-01-11 16:35:35

标签: grails has-many

我有3节课:

//jasperPrint is the JasperPrint object retrieved after fill
List<JRPrintPage> pages = jasperPrint.getPages();
if (pages.size() == 0) {
    // No pages
}

我想用

class Author {
    static hasMany = [books: Book]
    static belongsTo = [company: Company]
    String name
}

class Book {
     static mapping = {
        collection "documents"
        id generator: 'assigned',index: true, indexAttributes:[background:true, unique:true, dropDups:true] 
    }
    String id
    String name
}

class Company {
     static mapping = {
        collection "documents"
        id generator: 'assigned',index: true, indexAttributes:[background:true, unique:true, dropDups:true] 
    }
    String id
    String name
}

但运行此Grails时会从数据库中检索所有Book对象。

我只需将这些书籍作为作者的标识符,我不会使用这些对象。

我有办法强制Grails不要从数据库中获取图书和公司吗?

我试图使用:

Author author = Author.getByCompanyAndBook(1,1);

但仍然加载了所有图书和公司。

编辑:

我使用mongo db作为我的数据库。

1 个答案:

答案 0 :(得分:0)

这很奇怪 - 默认情况下收藏是懒惰的,因此在您访问books属性之前,让作者不应该检索书籍集合中的任何内容。但无论如何,即使它按预期工作,我建议您避免映射集合。请参阅this talk,其中显示了为什么集合不必要的昂贵,并提供了降低成本的解决方法。