Hi,
I have a parent class P which is associated with one-to-many relationship with a children class C (children on the many side)
Here are the partial class P and class C codes
Code:
public class P implements Serializable {
private int PID;
private Set thechildrens;
public getPID() {
return PID;
}
public Set getThechildrens() {
return thechildrens;
}
public int hashCode() {
return new HashCodeBuilder()
.append(getPID())
.toHashCode();
}
}
public class C implements Serializable {
private int CID;
private P theparent;
public getCID() {
return CID;
}
public getTheparent() {
return theparent;
}
public int hashCode() {
return new HashCodeBuilder()
.append(getCID())
.toHashCode();
}
}
Here are the mapping
Code:
<class
name="P"
table="P"
>
<id
name="PID"
type="int"
column="PID"
unsaved-value="0"
>
<generator class="identity" />
</id>
<!-- bi-directional one-to-many association to C-->
<set
name="thechildren"
lazy="true"
inverse="true"
cascade="save-update"
>
<key>
<column name="PID" />
</key>
<one-to-many
class="C"
/>
</set>
</class>
<class
name="C"
table="C"
>
<id
name="CID"
type="int"
column="CID"
unsaved-value="0"
>
<generator class="identity" />
</id>
<!-- bi-directional many-to-one association to P-->
<many-to-one
name="P"
class="P"
not-null="true"
>
<column name="PID" />
</many-to-one>
</class>
My problem is, I use a HashSet to store the references to different children object in the parent object, using the following code
Code:
P parent = new P();
P.setThechildren(new HashSet());
C children1 = new C();
children1.setParent(P);
C children 2 = new C();
children2.setParent(P);
P.getThechildren().add(children1);
P.getThechildren().add(children2);
Then I persist parent. I suppose all "parent", "children1", "children2" would be persisted because of the save-update cascade. It turns out that only "parent", "children1" are persisted, and "parent" only has one child which is "children1"
When I debug, I find that it is because the function hashCode() in class C use CID to return the hashcode. Before being persisted, CID of object children1 and children2 has not been initialized yet, and they have the same unsaved value as 0. Therefore, these 2 objects return the same hashcode, when putting them to the Set thechildrens in object P, only 1 of them have been inserted.
So if the key of objects in class C has to be generated from the database (being "identity"), and there are no other fields that can distinguish two different objects in C, how can I add them to the set maintained in the parent class (that is P)? Maybe there are some simple ways or workaround, but I can't think of them. I think it may be a common problem others may have experienced and solved. So any one can give me some ideas? Many thank. I used Hibernate 2.0.3, MySQL 4.0.12