2012-11-28 199 views
4

我有一個類叫做School它有很多Students,所以現在當我使用School.read(id)School情況下,我不希望所有的學生急切地取出,所以我改變抓取策略來lazyGrails領域關係

但現在它會獲取所有students當我將訪問school.students,我想手動設置前5 students然後如果需要5-10,等等

我們如何自定義懶取這樣?

School有許多Student

StudentSchool沒有關係單獨

回答

2

您可以自定義多少結果使用BATCHSIZE懶加載過程中獲取:

class Book { 
… 
static mapping = { 
    batchSize 10 
    } 
} 

Grails documentation

編輯

與其說School.students你可以創建一個簡單的服務,您的查詢

class SchoolService{ 

def getLastStudents(School school, int max, int offset){ 
     // (Not tested but should be something like this) 
     def query = "select student from School school join school.students student where school=:school" 
     def students = School.executeQuery(query, [school: school], [max: max, offset: offset]) } 

} 

然後調用schoolService.getLastStudents(school, 10, 0)例如,以獲得最後的10名學生。

您可以閱讀official documentation中關於Gorm標準的全部內容。

+0

如果我們沒有指定它,當我們訪問school.students時它會將所有學生加載到內存中,還是會在我們遍歷列表時加載? – user602865

+0

並且我可以只查詢第一次獲取前10名學生 – user602865

+0

是的,它會在您訪問school.students時加載所有學生。使用批量大小將會減少Hibernate對您的數據庫執行的查詢次數(例如,1個查詢將檢索10個對象,而不是10個查詢)。所以在你的情況下,我會建議你創建一個限制設置爲10的自定義查詢來獲得你的前10名學生。 –