I have inherited a bit of Java code that uses Hibernate. Some of the people using this code are now reporting that they are getting NullPointerExceptions all over the place.
I've been able to track this down and found that when we execute a query that pulls a list of objects from the database, that has a list of objects (that get pulled from a different table) Hibernate seems to be leaving holes in the list (NULL values). So the list may look something like:
Object
Object
NULL
Object
The code we are using to pull the information out of the database is:
List<PrinterGroup> groups =
this.getSession().createQuery( "from PrinterGroup" ).list();
And then inside each PrinterGroup is a list of Filters that have the NULL values in them.
While I could go around and find every instance were we loop over this list and add a NULL check I feel it is a bandaid fix, and there has to be a way to tell Hibernate to not pull null values in.
EDIT:
EDIT2:
So the database seemed to be confusing. The PrinterGroup -> Filter relationship is a one to many relationship. So PrinterGroups have a list of filters. The problem is that list of filters has null values in it when it comes out of the database (There are no null values in the database by the way) and the list comes out looking like above.
EDIT3:
Here is the mapping relavant picese in the PrinterGroup HBM
<subclass name="PrinterGroup" discriminator-value="PG">
<list name="filters"
lazy="true"
table="PG_FILTER"
inverse="false"
cascade="all-delete-orphan">
<key>
<column name="PG_ID" not-null="false"/>
</key>
<index column="LISTPOSITION"/>
<one-to-many class="Filter"/>
</list>
And the Filter is a pretty basic POJO mapping.
Is this collection mapped with a <list>
(or other indexed collection) and <list-index>
?
All collection mappings, except those with set and bag semantics, need an index column in the collection table. An index column is a column that maps to an array index, or List index, or Map key. ... The index of an array or list is always of type integer and is mapped using the element. The mapped column contains sequential integers that are numbered from zero by default.
I would imagine that when using an indexed collection, if your index column has gaps in it (i.e. it has values like 0
, 1
, 3
, 7
) that Hibernate would populate the resulting List
with empty elements at the expected places.
List<PrinterGroup> groups = this.getSession().createCriteria( PrinterGroup.class ).add(Restrictions.isNotNull("filters")).list();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With