hibernate 持久化对象经常需要重写hashcode和equals方法,什么情况下需要重写呢。
1.需要将对象放到set集合中
2.当需要比较对象不同的实例是否相等时
重写的方式:
1.eclipse自动生成
2.根据需要自己写
如果不写的话,hibernate会根据对象在内存中的地址来判断两个实例是否相等,最好是按照业务需求来写,如下,一个信息类,我设置了两个业务键,标题和发布时间,因为同一个时间发两个标题一样的几率很小小。。
/** * * @Override */ public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((publishingtime == null) ? 0 : publishingtime.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Information other = (Information) obj; if (publishingtime == null) { if (other.publishingtime != null) return false; } else if (!publishingtime.equals(other.publishingtime)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; }