Session session = sessions.openSession(); Object obj1 = session.load(User.class, new Integer(1)); Object obj2 = session.load(User.class, new Integer(1)); session.close(); System.out.println(obj1 == obj2);上面这个程序片段将会显示true的结果,表示obj1与obj2是参考至同一对象,但如果是以下的情况则会显示false:
Session session1 = sessions.openSession(); Object obj1 = session1.load(User.class, new Integer(1)); session1.close(); Session session2 = sessions.openSession(); Object obj2 = session2.load(User.class, new Integer(1)); session2.close(); System.out.println(obj1 == obj2);原因可以参考 简介快取(Session Level) 。
public class User {
....
public boolean equals(Object o) {
if(this == o) return true;
if(id == null || !(o
instanceof User)) return false;
final User user == (User) o;
return this.id.equals(user.getId());
}
public
int hashCode() {
return id == null ? System.identityHashCode(this) :
id.hashcode();
}
}
这个例子取自于Hibernate in
Action第123页的范例,然而这是个不被鼓励的例子,因为当一个对象被new出来而还没有save()时,它并不会被赋予id值,这时候就不适用这个方法。 public class Cat {
...
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof
Cat)) return false;
final Cat cat = (Cat) other;
if (!getName().equals(cat.getName())) return false;
if
(!getBirthday().equals(cat.getBirthday())) return false;
return
true;
}
public int hashCode() {
int result;
result = getName().hashCode();
result = 29 * result +
getBirthday().hashCode();
return result;
}
}
这个例子不是简单的比较id属性,而是一个根据商务键值(Business
key)实作equals()与hasCode()的例子,当然留下的问题就是您如何在实作时利用相关的商务键值,这就要根据您实际的商务需求来决定了。
愿意的话,还可以使用org.apache.commons.lang.builder.EqualsBuilder与
org.apache.commons.lang.builder.HashCodeBuilder来协助定义equals()与hashCode(),
例如:
package onlyfun.caterpillar;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class User {
....
public boolean equals(Object obj) {
if(obj == this) {
return true;
}
if(!(obj instanceof User)) {
return false;
}
User user = (User) obj;
return new EqualsBuilder()
.append(this.name, user.getName())
.append(this.phone, user.getPhone())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(this.name)
.append(this.phone)
.toHashCode();
}
}