2013-02-05 32 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