Using the automatically generated Hibernate object identifier in equals and hashcode methods

Lovely equals and hashcode, the whole theory is here as well as here

I decided to use the automatically generated identifier in equals () and hashcode () in a number of objects of the hibernation object / object.

However, a number of websites say that you should never do this because of the risk of persisting the object in the database for the first time while it is in the process of comparing or using hashcode.

My point is that in most cases this is much more unlikely than any other mutable field.

Individual domain objects have an identifier created once when they are first created, while almost all other fields can be changed during normal business processes (even a unique username can be changed ...).

And in many of my domain objects, a unique identifier is pretty much the only suitable field to consider (Person, Address, Pet, ... Customer, etc.? Combining fields is a good idea, but never using automatically generated id, I think not good advice.

Did I miss something else?

+4
source share
3 answers

You should read Equals and HashCode on the Hibernate wiki.

equals , hashCode , . equal, .

, , , , . .

+3

, , - . " " equals hashCode , Hibernate ID , , Hibernate . hashCode , " # 3" // equals/hashCode. , , Set , , hashCode .

, , , , , Hibernate. , setId(someNewId), , , , , .

Hibernate - equals hashCode, . , Hibernate, , hashCode, , . Hibernate -.

, . , , .

equals hashCode, Assert.notNull(id) equals hashCode .

, ,

+1

- Set . , , - , Set. , Set equals()/hashCode() ( , ).

Then I changed it to the actual creation and assignment of the identifier myself, which was a much better solution.

Read this article, it accurately explains the problem: dont-let-hibernate-steal-your-identity

0
source

All Articles