[英]Grails GORM Domain class relationship
Grails 1.1.1 Goovy 1.5.7
在這樣的關系中:
作者1-n圖書n-1出版商
在Grails中定義:
class Author {
String firstName
String lastName
static hasMany = [books: Book]
static constraints = {
books(nullable: true)
}
}
class Book {
String title
Author author
Publisher publisher
static constraints = {
author(nullable: true)
publisher(nullable: true)
}
}
class Publisher {
String name
static hasMany = [books: Book]
static constraints = {
books(nullable: true)
}
}
我想用出版商和作者的值加載一本書。 當我查詢到一本書時:
def book2 = Book.findAllByAuthor(author)
我得到了與助理關聯的響應,但發布者在另一個查詢中僅具有id和name類:
def book3 = Book.findAllByPublisher(publisher)
我得到相反的結果,我有帶出版商數據的書,但作者只有ID和類名。
定義的模型中的錯誤在哪里? o查詢方式有誤嗎?
編輯:
我需要這樣的方式僅使用查詢來檢索值:
def book2 = Book.findAllByAuthor(author, [fetch:[publisher:'eager']])
在這一本書中,我可以管理發布者的價值。
問題:如果出版商有hasmany
或Domain
相關問題,那本書我能夠閱讀屬性嗎?
謝謝。 謝謝。
默認情況下,懶惰獲取與gorm關聯一起使用。 如果要啟用急切獲取,可以通過將以下映射塊添加到Author域類來修改ORM DSL:
static mapping = {
books lazy:false
}
或者您可以在定義圖書關系之后通過添加以下代碼來更改域對象中的提取模式。
static fetchMode = [books:"eager"]
對您的Publisher域對象執行相同操作將使您能夠完成所需的工作。 您確實要注意可能會加載比預期更多的數據的后果。
get()方法是否應該返回您要查找的內容? 示例:def book2 = Book.get(作者)
您最好使用Criteria並明確定義應該急切加載的關系。 只需在查詢中提及關系即可。
例:
def c = Teacher.createCriteria()
List<Teacher> results = c.list {
subjects {
attendees {}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.