import java.util.Objects;
public class User {
private int id;
private String name;
private int age;
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age);
}
}
try {
sf=HibernateUtil.getSessionFactory();
session=sf.getCurrentSession();
ts=session.beginTransaction();
User u3=session.get(User.class, 3);
session.evict(u3);
User u4=session.get(User.class, 3);
System.out.println(u3==u4);
ts.commit();
}
测试结果:
hashCode相同,对象不一定相同
必须要地址的散列码相同才可以是同一个对象
重写后比较的方式改变,将不再比地址