equals方法是判断PO是否相等的重要方法,当然覆写equals方法的同时要求也是要覆写hashCode方法的,以下实例了PO中覆写的一般方式.
package test.base;
import java.io.Serializable;
public abstract class UserInfo implements Serializable {
private int hashCode = Integer.MIN_VALUE;
// primary key
private java.lang.String userId;
// fields
private java.lang.String userName;
private java.lang.String userAccount;
public UserInfo() {
}
public UserInfo(java.lang.String userId) {
this.setUserId(userId);
}
public java.lang.String getUserId() {
return userId;
}
public void setUserId(java.lang.String userId) {
this.userId = userId;
//因为hashCode()方法和主键值有关,重新设置主键值时要还原hashCode值.
this.hashCode = Integer.MIN_VALUE;
}
public java.lang.String getUserName() {
return this.userName;
}
public void setUserName(java.lang.String userName) {
this.userName = userName;
}
public java.lang.String getUserAccount() {
return this.userAccount;
}
public void setUserAccount(java.lang.String userAccount) {
this.userAccount = userAccount;
}
public boolean equals(Object obj) {
if (null == obj)
return false;
if (!(obj instanceof test.base.UserInfo))
return false;
else {
test.base.UserInfo mObj = (test.base.UserInfo) obj;
if (null == this.getUserId() || null == mObj.getUserId())
return false;
else
return (this.getUserId().equals(mObj.getUserId()));
}
}
public int hashCode() {
//这样做的目的就是hashCode值只需要计算一次.
if (Integer.MIN_VALUE == this.hashCode) {
if (null == this.getUserId())
return super.hashCode();
else {
String hashStr =
this.getClass().getName()
+ ":"
+ this.getUserId().hashCode();
this.hashCode = hashStr.hashCode();
}
}
return this.hashCode;
}
}
本文地址:http://com.8s8s.com/it/it12525.htm