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);

章のコレクションのない本が必要な場合があります。休止状態でこれを行う方法は?

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悪です。バグの原因となり、コードが読みにくくなるため、疫病のような null コレクションは避けたいと考えています。

于 2013-02-05T12:20:39.907 に答える