简体   繁体   English

等于具有延迟加载字段的bean

[英]Equals on beans with lazy loaded fields

Let's say I have a bean: 假设我有一个豆子:

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
}

This bean is mapped from/to a database using MyBatis or any other persistent framework. 使用MyBatis或任何其他持久性框架将此bean映射到数据库。 What matters is that users are lazy loaded (they are loaded from DB when getUsers() is first time called). 重要的是用户是延迟加载的(当第一次调用getUsers()时,它们是从数据库加载的)。

My question is, what equals method should have this bean? 我的问题是,什么等于方法应具有此bean?

Should I include the id field (which is its database primary key)? 我应该包括id字段(这是它的数据库主键)吗?

Should I include the users list? 我应该包括用户列表吗? Equals is called very often on Java objects (eg. when they are stored in collections), so this would kill the lazy approach. 在Java对象上经常调用Equals(例如,当它们存储在集合中时),因此这将消除惰性方法。

You said that id is the primary key, so id is unique. 您说id是主键,所以id是唯一的。 Because the id is unique than you only need that field in the equals method. 因为id是唯一的,所以您在equals方法中只需要该字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM