Easy toString/equals/hashcode
A simple, standard and reusable way of creating toString, equals and hashcode methods in your classes/beans can be found in the jakarta commons.lang package:
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public class BaseBean {
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
// EDIT: this hashCode-implementation seems to break Hibernate:
// it throws a LazyInitializationException
// return HashCodeBuilder.reflectionHashCode(this);
//
// using this implementation for now
return new HashCodeBuilder(25, 71) // random odd numbers
.append(this.getId()) // a field in BaseBean, not shown for brevity
.append(super.hashCode()) // using the standard hashcode too
.toHashCode();
}
}
Mark your collections with the transient keyword and do not include them into the hash code.
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, false);
}
Regards,
Cyrill