- If two objects are equal, they must have the same hashcode.
- equals() method, by default, checks whether two references refer to the same in-memory instance on the Java heap
You can rely on Entity identifier to compare your Entity by using equals
public boolean equals(Object o) {
if(o == null)
return false;
Account account = (Account) o;
if(!(getId().equals(account.getId())))
return false;
return true;
}
But what happens when you have a non-persisted Entity. It will not work because its Identifier has not been assigned.
So Let's see what Java Persistence with Hibernate Book talks about it
A business key is a property, or some combination of properties, that is unique for each instance with the same database identity.
So
It is the natural key that you would use if you weren’t using a surrogate primary key instead.
So let's suppose you have a User Entity and its natural keys are firstName and lastName (At least, his/her firstName and lastName often does not change). So it would be implemented as
public boolean equals(Object o) {
if(o == null)
return false;
if(!(o instance of User))
return false;
// Our natural key has not been filled
// So we must return false;
if(getFirstName() == null && getLastName() == null)
return false;
User user = (User) o;
if(!(getFirstName().equals(o.getFirstName())))
return false;
if(!(getLastName().equals(o.getLastName())))
return false;
return true;
}
// default implementation provided by NetBeans
public int hashcode() {
int hash = 3;
hash = 47 * hash + ((getFirstName() != null) ? getFirstName().hashcode() : 0)
hash = 47 * hash + ((getLastName() != null) ? getLastName().hashcode() : 0)
retrun hash;
}
It works fine! I use even with Mock objects like repositories, services etc
And about toString() method, as said by @Bozho, you can put whatever information is interesting. But remember some web frameworks, like Wicket and Vaadin, for instance, use this method to show its values.