Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice when implementing equals() for entities with generated ids

Tags:

java

hibernate

If I have a table with columns A, B, C, D
 A: auto-generated id (PK)
 B & C: combination must be unique (these are the columns that actually define identity in the business sense)
 D: some other columns

Now, if I'll create business objects based on this table (e.g. in Java), which one would be a better implementation of the equals() method:

  1. define equality based on A
  2. define equality based on B and C

or, it wouldn't really matter which of the two I choose.

like image 733
willy wonka Avatar asked Dec 01 '10 10:12

willy wonka


People also ask

How does equals () method work What does it do?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

What is the use of implementing hashCode () and equals () method?

Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.

What is equals () and hashCode () method?

The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.

What is the default implementation of equals method?

equals() is a method defined in the Object class thus the default implementation of the . equals() method compares the object references or the memory location where the objects are stored in the heap. Thus by default the . equals() method checks the object by using the “==” operator.


1 Answers

Definitely B and C, because you want the equals() contract to be valid even before entities are persisted. You say yourself:

these are the columns that actually define identity in the business sense

If that is the case, then that is the logic equals() should use. Database keys are the database's concern and should be of no concern to your business layer.

And don't forget to use the same properties in hashcode(), too.

like image 137
Sean Patrick Floyd Avatar answered Oct 15 '22 09:10

Sean Patrick Floyd