Getting started 17 - Implement Equals and Hashcode
Hibernate does not guarantee the data objects obtained at different times, and whether it is referred to to the same location of memory, using == to compare the data of the two objects that represent the same data in the database, while Object preset Equals () Itself is the memory reference of the comparison object, if you need to compare whether the data of the two objects after the query is the same (for example, when the object is stored to SET), you must do Equals () and havehcode (). A method of actual equals () and hashcode () is based on the database's Identity, one method is to acquire the ID value of the object through the getId () method, such as if the ID is String, an actual example as follows:
User.java
PUBLIC CLASS User {
....
Public Boolean Equals (Object O) {
IF (this == o) return true;
IF (ID == NULL ||! (o instanceof user)) Return False;
Final user user == (user) O;
Return this.id.equals (user.getid ());
}
Public int.comode () {
RETURN ID == NULL? System.Identityhashcode (this): id.hashcode ();
}
}
This example is taken from the example of Hibernate In Action, however, this is an example that is not encouraged, because when an object is coming out by New, it will not be given the ID value, at this time This method is not applicable. A comparison method is to compare according to the real value of the actual included object, and give an example in the reference manual:
Cat.java
PUBLIC CLASS CAT {
...
Public Boolean Equals (Object Other) {
IF (this == other) return true;
IF (! (家 instanceof cat) RETURN FALSE;
Final Cat Cat = (CAT) Other;
IF (! getname (). Equals (cat.getname ())) Return False;
IF (! getBIRTHDAY (). Equals (cat.getbirdhday ())) Return False;
Return True;
}
Public Int hashcode () {
Int result;
Result = getname (). hashcode ();
Result = 29 * Result getBIRTHDAY (). hashcode ();
Return Result;
}
}
We no longer compare the ID attribute, this is an example of the business key (Business key), which is an example of the Hascode (), of course, how you use the related business key value when you do This will be determined according to your actual business needs.