简体   繁体   中英

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. What matters is that users are lazy loaded (they are loaded from DB when getUsers() is first time called).

My question is, what equals method should have this bean?

Should I include the id field (which is its database primary key)?

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.

You said that id is the primary key, so id is unique. Because the id is unique than you only need that field in the equals method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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