I wasn’t able to create an issue for this and I’m still unsure whether I’m doing something wrong with hibernate here. So I created this post first.
I observed some strange behavior when executing a query for entities on the “Many”-end of a one-to-many association, when the association should be fetched EAGERly.
The problem seems to be that after fetching the result of the query, the associated “parent” is also fetched and with it all it’s “children”. But when doing this, the Objects for the children seem to be put in the PersistentSet before they are initialized.
Because I implemented hashCode on the Child Entity and used some of it’s fields for this, the objects in the set will “change” their hashCode after the fields have been initialized.
I created a small example project which has two failing tests with demonstrate the issue by showing that the the fetched entity can’t be removed from its parents collection of children.
the project is based on Spring but the second Test in “RemoveChildTest” uses the Hibernate Session directly instead of Springs Data JPA stuff.
This might be a Kotlin issue, so I would suggest that you try the same app without Kotlin.
The underlying HashSet is only built after the contents are fully initialized, so this shouldn’t happen. What I could imagine, is that the collection contents are proxies and because your equals/hashCode implementations use the fields directly instead of getters, the hashCode might be based on null values somehow. I simply don’t know what impact Kotlin can have here, hence my ask for you to try with plain Java first before anyone digs deeper.
The project has been updated and switched to java but the problem is still reproducible.
I added some code to the hashCode method in Book so you can see that the title field is actually null when the object is into the PersistentSet in
org.hibernate.collection.spi.PersistentSet.injectLoadedState
DISCLAIMER: I used copilot to transform the project from kotlin to java but had a look at the result and couldn’t find any relevant issues with the result.