0
豆比方說,我有一顆豆:的Equals與延遲加載領域
class File {
private id;
private String name;
private User author;
private List<User> users;
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false
}
if (!(obj instanceof File)) {
return false;
}
File other = (File) obj;
if (getId() == null) {
if (other.getId() != null) {
return false;
}
} else if (!getId().equals(other.getId())) {
return false;
}
if (getName() == null) {
if (other.getName() != null) {
return false;
}
} else if (!getName().equals(other.getName())) {
return false;
}
if (getAuthor() == null) {
if (other.getAuthor() != null) {
return false;
}
} else if (!getAuthor().equals(other.getAuthor())) {
return false;
}
if (getUsers() == null) {
if (other.getUsers() != null) {
return false;
}
} else if (!getUsers().equals(other.getUsers())) {
return false;
}
return true;
}
...
getters/setters
}
這豆是從/使用MyBatis的或任何其他持久性框架數據庫映射。 重要的是,用戶延遲加載(當第一次調用getUsers()時,它們從數據庫加載)。
我的問題是,什麼等於方法應該有這個bean?
我應該包含id字段(這是它的數據庫主鍵)嗎?
我應該包含用戶列表嗎? Equals在Java對象上經常被調用(例如,當它們被存儲在集合中時),所以這會殺死懶惰的方法。
是的,但該平等僅限於數據庫級別。在應用程序中,當兩個文件具有相同的名稱,作者和評論時,它們被認爲是相同的。他們不是嗎?例如,在GUI中進行編輯時。您必須比較新舊文件以獲得「髒狀態」。 – Behnil