I have a MySql sql statement from a legacy php application that is the following:
SELECT * FROM document WHERE category_id = '$categoryId' OR (category_id IS NULL AND '$categoryId' = '0') ORDER BY list_order;
As one can see, this statement allows for the finding of documents that have no categories set to them.
I'm trying to have it behave in the same way in Hibernate.
And so, I came up to the following code.
Code:
<hibernate-mapping>
<class name="com.thalasoft.learnintouch.core.domain.Document" table="document" dynamic-insert="true" dynamic-update="true">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<version name="version" type="int">
<column name="version" not-null="true" />
</version>
<many-to-one name="documentCategory" class="com.thalasoft.learnintouch.core.domain.DocumentCategory" cascade="all" fetch="select">
<column name="category_id" />
</many-to-one>
<property name="reference" type="string">
<column name="reference" length="50" not-null="false" />
</property>
<property name="description" type="string">
<column name="description" not-null="false" />
</property>
<property name="file" type="string">
<column name="file" length="50" not-null="true" />
</property>
<property name="hide" type="boolean">
<column name="hide" not-null="false" />
</property>
<property name="listOrder" type="int">
<column name="list_order" not-null="true" />
</property>
</class>
</hibernate-mapping>
Code:
public List<Document> findByCategoryOrderById(DocumentCategory documentCategory) {
Criteria criteria = getSession().createCriteria(Document.class);
criteria.add(Restrictions.eq("documentCategory", documentCategory));
criteria.addOrder(Order.asc("id"));
return criteria.list();
}
But my test fails when trying to retrieve the one document that has no category given to it.
documentCategories = documentDao.findByCategory(null);
assertEquals(1, documentCategories.size());
testException = java.lang.AssertionError: expected:<1> but was:<0>]]
Code:
@Test
public void testFindByCategory() {
DocumentCategory documentCategory = new DocumentCategory();
documentCategory.setName("images");
documentCategory.setListOrder(0);
documentCategory = documentCategoryDao.makePersistent(documentCategory);
document1 = documentDao.makePersistent(document1);
document0 = documentDao.makePersistent(document0);
document0.setDocumentCategory(documentCategory);
List<Document> documentCategories = documentDao.findByCategory(documentCategory);
assertEquals(1, documentCategories.size());
documentCategories = documentDao.findByCategory(null);
assertEquals(1, documentCategories.size());
}
Any idea ?
Thanks !