Reputation: 14370
When I execute my program without implementing hashcode()
and toString()
then it works fine. But as soon as I include hashcode()
and toString()
then I get this "illegal access to loading collection" error.
My hbm files are
1) booking.hbm.xml
<many-to-one name="userId" class="User" column="user_id"
insert="true" update="true" cascade="save-update" >
</many-to-one>
<many-to-one name="flightId" class="FlightSchedule"
column="flight_id" cascade="all" not-null="true">
</many-to-one>
<set name="passenger" table="passenger79215" lazy="false"
inverse="true" cascade="save-update">
<key column="reference_id" />
<one-to-many class="Passenger" />
</set>
2) Passenger.hbm.xml
<many-to-one name="referenceid" class="Booking" lazy="false"
insert="true" update="true" column="reference_id "
cascade="save-update">
</many-to-one>
3) User.hbm.xml
<set name="booking" table="bookings79215" lazy="true"
inverse="false" cascade="save-update">
<key column="user_id" />
<one-to-many class="Booking" />
</set>
Can anyone explain the error?
Upvotes: 7
Views: 15846
Reputation: 3163
Your hashcode and equals methods are not working properly. Make sure that they are correct. toString()
has nothing to do with collection classes but hashcode and equals does.
I assume that you have overridden both hashcode and equals and not only hashcode.
Object#hashCode()
(Java Platform SE 7 )
Upvotes: 7
Reputation: 373
I had the same error but with a different resolution. Like the OP I'm using Apache's hashcode builder. My objects are Parent and Child with a one-to-many relationship. The child includes Parent as a member so that the foreign key gets set properly.
The problem is that the hashcode builder uses all the member fields but when Child is being created its Parent hasn't finished loading yet. When the hashcode builder references the Parent member Hibernate throws the exception because Parent is still loading.
The fix was to exclude the parent reference from the hashcode builder in Child's hashCode and equals:
@Override
public boolean equals(final Object obj)
{
return EqualsBuilder.reflectionEquals(this, obj, "parent" );
}
@Override
public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this, "parent" );
}
Upvotes: 0
Reputation: 23950
I think you should not use the id field (managed by hibernate) in equals and/or hashCode.
Equals and hashCode should be implemented as a business logic equals.
Upvotes: 2