Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How hibernate uses equals() and hashCode()?

If you load an entity from db and modify it somehow, will hibernate use equals/hashCode to compare current state of entity with it's snapshot to determine if sql update needs to be performed?

If it does such comprasions, I have another question: if equals will return true, will hibernate think that entity did not changed or attempt to use it's default comprasion (to be sure)?

like image 650
Jeriho Avatar asked Nov 08 '11 12:11

Jeriho


2 Answers

Please see Equals and HashCode from the JBoss Community website. From there:

To avoid this problem we recommend using the "semi"-unique attributes of your persistent class to implement equals() (and hashCode()). Basically you should think of your database identifier as not having business meaning at all (remember, surrogate identifier attributes and automatically generated vales are recommended anyway). The database identifier property should only be an object identifier, and basically should be used by Hibernate only. Of course, you may also use the database identifier as a convenient read-only handle, e.g. to build links in web applications.

In other words, Hibernate uses equals and hashCode for identity, not to see if an object has been modified. It uses attribute by attribute comparisons for that.

like image 124
Matthew Farwell Avatar answered Oct 21 '22 01:10

Matthew Farwell


Not an Hibernate expert, but you may find this section of manual enlightening.

like image 26
Victor Sorokin Avatar answered Oct 21 '22 02:10

Victor Sorokin