hibernate中 联合主键的主键类需重写equals() hashCode() 返回的值有什么用? 怎么写?

主键类需实现Serializable接口,重写equals() hashCode() 方法.
equals() hashCode()返回的值有什么用?
返回true 或 false 会怎么样??
该怎么写这两个方法呢...

写一个测试的主键类吧..
public class TeacherPK implements Serializable{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

//@Override

//@Override

}

//他会用equals方法判断两个对象是否相等,用hashCode方法帮助其存储在hashSet,hashMap。

public boolean equals(Object obj) {
if(obj = null || obj.getClass() != this.getClass()){
return false;
}
TeacherPK other = (TeacherPK) obj;
if(this.name == null) {
return other.name == null;
}
return this.name.equals(other.name);
}

public int hashCode() {
if(this.name == null) {
return 0;
}
return this.name.hashCode();
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-03-27
public boolean equals(Object other){ if(this != other) return false; if(!(other instanceof TeacherPK )) return false; TeacherPK pk = (TeacherPK )other; if(!this.getName().equals(pk.getName)) return false; if(!this.getId().equals(pk.getId)) return false; return true; } //override hashCode() public int hashCode(){ return new HashCodeBuilder() .append(this.getId()) .append(this.getName()) .toHashCode(); }