2013-02-05 37 views
0

這是一個表結構:休眠,如何跳過收集

<class name="test.Book" table="book" > 
    <cache usage="nonstrict-read-write"/> 
    <id column="id" name="id" type="int" unsaved-value="-1"> 
    <generator class ="increment"/> 
    </id> 
    <property column="title" name="title" type="string" not-null="false" /> 
    <property column="description" name="description" type="string" not-null="false" /> 
    <list name="chapters" table="bookChapters" cascade="persist"> 
    <cache usage="nonstrict-read-write"/> 
    <key column="bookChapter_id" /> 
    <list-index column="rank"/> 
    <many-to-many column="chapter_id" class="test.Chapter" /> 
    </list> 
</class> 

每次當我拿到書有章節的採集:

DetachedCriteria crit = DetachedCriteria.forClass(Book.class, id); 
List<Book> bookList = getHibernateTemplate().findByCriteria(crit); 

有時候,我需要一本沒有書的收藏章節。如何用Hibernate做到這一點?

回答

0

一本書有章節。如果它沒有章節,收集將empy。那就是你想要的。它允許迭代通過章節做

for (Chapter chapter : book.getChapters()) { 
    ... 
} 

,而不是

if (book.getChapters() != null) { 
    for (Chapter chapter : book.getChapters()) { 
     ... 
    } 
} 

它允許測試如果這本書做

if (!book.getChapters().isEmpty()) 

,而不是通過做

if (book.getChapters() != null && !book.getChapters.isEmpty()) 
有章

null是邪惡的。您希望避免像鼠疫這樣的空集合,因爲它們會導致錯誤,並使代碼不易讀。

+0

我不需要從數據庫中獲取章節,即無論有多少章我都不需要它, – Lazy

+0

用你的暱稱,你應該明白:默認情況下,收藏會被加載* lazily *。所以,如果你不訪問章節的集合,hibernate將不會加載數據庫中的章節。只有當你調用collection(size(),iterator())方法時,hibernate纔會加載這些章節。 –

+0

正確,但我有不同的默認模式'' 因此,在某些情況下,我可以將懶惰模式轉換爲「true」嗎? – Lazy