Source code below works fine in most cases:
- each AClass has 10 items in the bclasses list
- all BClass records (10) related to one AClass have rank between 0 and 9
Sometimes I've seen another behavior after updating of AClass:
- each AClass has 10 items in the bclasses list
- all BClass records (10) related to one AClass have rank between 0 and 18, i.e. 0, 10, 11, 12, 13, 14, 15, 16, 17, 18
Hibernate checks the maximum number in this list (18) and makes a decision to create a list of 19 items, all items between 1 and 9 IDs is null. As a result I have NullPointer in the setBclass method.
Some additional notes:
- There is no method on server side to add/delete BClass into/from the list
- Server side creates this list and set rank explicitly for each item in the list without gaps
Why rank values were changed ?
public class AClass implements Cloneable {
private int id = -1;
private List<BClass> bclasses;
public void setBclass(List<BClass> bclasses) {
this.bclasses= bclasses;
for (BClass bclass : bclasses) {
//do something with bclass
//sometimes some items in the list is null
}
}
}
public class BClass implements Cloneable {
private int id = -1;
private byte rank;
}
Mapping:
<class name="AClass" table="aclass" >
<cache usage="read-write"/>
<id column="id" name="id" type="int" unsaved-value="-1">
<generator class ="increment"/>
</id>
<list name="bclasses" table="bclass" cascade="all">
<cache usage="nonstrict-read-write"/>
<key column="aclass_id" />
<list-index column="rank"/>
<one-to-many class="bclass" />
</list>
</class>
<class name="BClass" table="bclass">
<cache usage="read-write"/>
<id column="id" name="id" type="int" unsaved-value="-1">
<generator class ="increment"/>
</id>
<property column="rank" name="rank" type="byte" />
</class>