簡體   English   中英

等於具有延遲加載字段的bean

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM