我有 3 個實(shí)體,學(xué)生、年級和班級。代碼如下所示。這只是一個樣本。學(xué)生班public class Student implements Serializable{ private static final long serialVersionUID = 1L; private String fullName; private long studentId; //omit getter/setter column mapped to db @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getFullName() == null) ? 0 : getFullName().hashCode()); result = prime * result + (int) (getStudentId() ^ (getStudentId() >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Student) return false; test other = (test) obj; if (getFullName() == null) { if (other.getFullName() != null) return false; } else if (!getFullName().equals(other.getFullName())) return false; if (getStudentId() != other.getStudentId()) return false; return true; }}學(xué)校班級:public class SchoolClass implements Serializable{ private static final long serialVersionUID = 1L; private String className; private long classId; //omit getter/setter column mapped to db @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (getClassId() ^ (getClassId() >>> 32)); result = prime * result + ((getClassName() == null) ? 0 : getClassName().hashCode()); return result; }所以我檢查了 hibernate doc 的 hashcode 和 equals,它對于 DB 中存在的實(shí)體來說工作得很好。我遇到的問題是在保存到數(shù)據(jù)庫之前對于新的瞬態(tài)實(shí)體對象。我使用 HashSet 專門針對 Student 和 SchoolClass 進(jìn)行了單獨(dú)測試,如果它嘗試添加相同的對象,集合的大小不會增加。
添加回答
舉報
0/150
提交
取消