[英]Equals on beans with lazy loaded fields
假设我有一个豆子:
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或任何其他持久性框架将此bean映射到数据库。 重要的是用户是延迟加载的(当第一次调用getUsers()时,它们是从数据库加载的)。
我的问题是,什么等于方法应具有此bean?
我应该包括id字段(这是它的数据库主键)吗?
我应该包括用户列表吗? 在Java对象上经常调用Equals(例如,当它们存储在集合中时),因此这将消除惰性方法。
您说id是主键,所以id是唯一的。 因为id是唯一的,所以您在equals方法中只需要该字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.