Search code examples
springmongodbspring-datamongo-javadbref

Check if User object exists in @DBRef List<User>


I'm making use of MongoDB, Spring Data and Spring MVC. I have a user model which has a list of contacts:

class User {
@DBRef
private List<User> contacts = new ArrayList<User>(); 

public List<User> getContacts() {
    return contacts;
}
}

I currently have 4 users inside my database. 1 user has a particular contact (who is referred to the same collection by id).

Now, I want to check whether a user has a particular contact. I use the following code:

User userLoggedIn = userService.getLoggedInUser(); //user object
User contact = userService.findById(contactId); //contact
if(userLoggedIn.getContacts().contains(contact)) {
    System.out.println("Has this contact.");
}

This output message is not shown. However, if I print the list of contacts of the user and their id's, I clearly see that the contact is inserted inside the list of the user.

I noticed that if I print the hashCode of the contact object and the one that is inside the list, I get a different value, so I assume that even though the details are the same, the object itself isn't.

How can I approach this problem by simply checking whether he is inside the list. Or should I just compare by id?

Otherwise stated: how can I check whether an object exists in the contacts list?


Solution

  • You should override an equals method in User.

    From JavaDoc:

    boolean contains(Object o)

    Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

    With equals you must override and hashCode

    http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/persistent-classes.html#persistent-classes-equalshashcode