Updating entity type using single table inheritance strategy

Hi all,
I am using single table inheritance for an entity (Cat) which has type column as discriminator column (Domestic, Wild). Another entity (Person) has collections of Cat as one-to-many relationship with orphanRemoval true.

I am facing issues trying to update one Cat entity (while trying to save Person) changing its type but keeping the id same. I see hibernate, tries an insert query with the new cat but it fails due to primary key constraint as it has same id as one already persisted (with different type). I was hoping hibernate would delete the existing one and then insert a new one but it’s not happening.

Another thing worth mentioning is how I am saving Person. I am not fetching existing Person from db and then updating. I am relying on hibernate to do a merge as I am setting the ids.

Is it possible to achieve what I am trying with current approach? or do I have to fetch the entities from db and update the collection myself before saving?

Please help!

I never tried what you are writing about here, but for Hibernate, the type of the entity is part of the identity, so changing that will naturally cause issues. You can, instead of using inheritance, put a field type into the base entity, and just work with that base entity. This way you avoid the type change and everything should work fine.

Thanks @beikov

Do you think overriding equals/hashcode will help in this case?

No, as this has to do with object identity. If the object is once created with a primary key and associated with a session, it just can’t change the type. What you could do is, remove the object, flush and clear the persistence context and finally persist the object with the new object type, but then you would also have to re-establish all the join-table/many-to-many associations.