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 做到这一点?

4

1 回答 1

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是邪恶的。您希望避免像瘟疫那样的空集合,因为它们会导致错误,并使代码的可读性降低。

于 2013-02-05T12:20:39.907 回答