CRITICAL
Rule Definition
This is important, since the object instance passed as other might be a proxy object, not the actual instance that holds the persistent state. This is the case when there are lazy associations between classes. This is one point where Hibernate is not completely transparent, but it's good practice to use accessor methods instead of direct instance variable access: when tuning the performance of the application, a lazy association might be required and the issue can occur.
This potential issue raises a ClassCastException and can cause the application to become unstable.
Remediation
Use the getter instead.
Violation Code Sample
public class PersitentSample implements Serializable {
private Long id;
private String field;
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public boolean equals(Object obj) {
if (this==obj)
return true;
if (id==null)
return false;
if (obj.getClass() != this.getClass()) return false;
final PersitentSample o = (PersitentSample) obj;
return this.field.equals(o.getField()); // VIOLATION
}
public int hashCode() {
return field.hashCode(); // VIOLATION
}
}
Fixed Code Sample
public class PersitentSample implements Serializable {
private Long id;
private String field;
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public boolean equals(Object obj) {
if (this==obj)
return true;
if (obj==null)
return false;
if (obj.getClass() != this.getClass())
return false;
final PersitentSample o = (PersitentSample) obj;
return this.getField().equals(o.getField()); // FIXED
}
public int hashCode() {
return getField().hashCode(); // FIXED
}
}
Reference
Hibernate in Action (ISBN 1932394-15-X) p 125, Java Persistence with Hibernate (ISBN 1-932394-88-5) p 400, The Java Persistence API page 400 - ISBN 1-932394-88-5
Related Technologies
JEE
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.