对象识别
重写equals()方法
public boolean equals(Object obj) {
if (this == obj) return true;
if(obj == null) return false;
if (!(obj instanceof User))
return false;
User other=(User)obj;
if(id!=other.id) {
return false;
}
if(age!=other.age) {
return false;
}
if(name != null && other.name != null) {
if(!name.equals(other.name)) {
return false;
}
}
if(gender != null && other.gender != null) {
if(!gender.equals(other.gender)) {
return false;
}
}
if(!birthday.equals(other.birthday)) {
return false;
}
return true;
}
重写hashcode()方法
public int hashCode() {
int result;
result = getName ().hashCode();
result = 29 * result + getBirthday().hashCode();
result = 29 * result + getAge();
return result;
}
对象识别方法
public void testObjectIndentify() {
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
User u1 = null, u2 = null;
try {
sf = hibernateUtil.getSessionFactory()
session = sf.getCurrentSession();
ts = session.beginTransaction();
u1 = (User)session.get(User.class,1);
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(ts != null) {
ts.rollback();
}
}
try {
sf = hibernateUtil.getSessionFactory();
session = sf.getCurrentSession();
ts = session.beginTransaction();
u2 = (User)session.get(User.class,1);
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(ts != null) {
ts.rollback();
}
}
System.out.println(u1 == u2);
System.out.println(u1.equals(u2));
}