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:
or, it wouldn't really matter which of the two I choose.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With