这是一个表结构:
<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 :(得分:0)
一本书有章节。如果它没有章节,那么该集合将是真实的。那正是你想要的。它允许通过
遍历章节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
是邪恶的。你想避免像瘟疫这样的空集合,因为它们会导致错误,并使代码的可读性降低。