I still am not sure why the class for composite-id must be serializable. But implement equals() and hashCode() methods so that your dont face some problems( possible ). This was mandatory in version 2.x and optional in 3.x for some reason.
Will give an example where implementing those methods can be helpful.
Always want to check, if a child object is existing in lazy collection before "adding/deleting" from parent. So when a user submits a request to "add/delete" few of the children, I get only primary key fields with which I construct object with primary key fields set. With this object I want to check if any persistent entity is existing in the parent collection of child objects. Without overriding equals() and hashCode(), I was not getting consistent results when I was checking for child entity availability in lazy collection. Even
Code:
Parent parent = (Parent) session.get( Parent.class, parentPrimaryKey );
Child addChild1 = new Child();
addChild1.setPrimaryKeyFields();
Child addChild2 = new Child();
addChild2.setPrimaryKeyFields();
Child deleteChild1 = new Child();
deleteChild1.setPrimaryKeyFields();
if ( ! parent.getChildCollection().contains( addChild1 ) ) {
parent.getChildCollection().add( addChild1 );
}
if ( ! parent.getChildCollection().contains( addChild2 ) ) {
parent.getChildCollection().add( addChild2 );
}
if ( parent.getChildCollection().contains( addChild1 ) ) {
parent.getChildCollection().remove( deleteChild1 );
}
// call to modify some of parents attributes
modifyNonPrimarykeyFieldsOfParent( parent );
session.saveOrUpdate( parent );
Without equals() and hashCode() I was getting
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:
If anyone has an idea for better solution, please let me know. For now, I am implementing equals() and hashCode() to make it work.