我有 3 个实体,学生、年级和班级。代码如下所示。这只是一个样本。学生班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; }}学校班级: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 中存在的实体来说工作得很好。我遇到的问题是在保存到数据库之前对于新的瞬态实体对象。我使用 HashSet 专门针对 Student 和 SchoolClass 进行了单独测试,如果它尝试添加相同的对象,集合的大小不会增加。
添加回答
举报
0/150
提交
取消