ORM基础——对象识别之重写对象equals
一、Object类的概述
(1)基本概念
Java.lang.Object类是所有类层次结构的根类,任何类都是该类的直接/间接子类。
(2)常用的方法
boolean equals(Object obj) - 用于判断调用对象是否与参数对象相等。
该方法默认比较两个对象的地址,与 == 的效果等效。
若希望比较对象的内容,则需要进行方法的重写。
若该方法重写了,则应该去重写hashCode()方法,为了满足hashCode()的常规协定
int hashCode() - 用于获取调用对象的哈希码值(内存地址的编号)并返回。
若两个对象调用equals()方法相等,则各自调用该方法得到的哈希码值必须相同。
若两个对象调用equals()方法不相等,则各自调用该方法的结果可以相同,
但最好不相同。
String toString() - 用于返回调用对象的字符串表示形式。
默认返回的字符串内容是:包名.类名@哈希码的无符号十六进制形式。
若希望返回其他内容,则需要进行方法的重写。
当使用print()/println()打印引用变量时,会自动调用toString()方法。
当使用字符串和引用变量进行拼接(+)时,会自动调用toString()方法。
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;
}
public int hashCode() {
int result;
result = getName ().hashCode();
result = 29 * result + getBirthday().hashCode();
result = 29 * result + getAge();
return result;
}
//manageUser.java
public void testObjectIndentifySession(){
Configuration cfg=null;
SessionFactory sf=null;
Session session=null;
Transaction ts=null;
try {
sf=HibernateUtil.getSessionFactory(); //sessionFactory的单态模式
session=sf.getCurrentSession();//保证每个读写线程有唯一的session实例
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);
System.out.println(u3.equals(u4));//因为是false,所以我们要重写equals()、hasCode()
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(ts!=null){
ts.rollback();
}
}finally{
//session.close();
//sf.close();
}
}