Home > Net >  Can't remove from DBRef set in Spring Boot application
Can't remove from DBRef set in Spring Boot application

Time:12-06

I have Group objects that have a @DBRef set of Users, and each user likewise has a @DBRef set of Groups:

public class Group {
    @Id
    private String id;
    @Indexed(unique = true)
    private String name;
    @DBRef(lazy=true)
    private Set<User> users;

    //...
}
public class User {
    @Id
    private String id;
    @Indexed(unique = true)
    private String email;
    private String password;
    private String role;
    @DBRef(lazy = true)
    private Set<Group> groups;
    //...
}

When I delete a User I of course have to remove him from his groups:

Set<Group> subscribedGroups = userRepository.findByEmail(email).getGroups();
for (Group g : subscribedGroups) {
    Set<User> users = g.getUsers();
    users.remove(user);
    g.setUsers(users); // not sure if this line is necessary but it doesnt work regardless
    groupRepository.save(g);
}

This isn't working. remove(user) is returning false for some reason. It should be working; I printed the Ids of every member of users, then user.getId(), then the result of remove(user):

List of users:
61abd6f1c81ab948c31641f2

User to delete: 61abd6f1c81ab948c31641f2
Result of removal: false

CodePudding user response:

You seem to be used to JPA, which employs various means of marvelous magic to ensure that (within a particular transaction) if you see the same database record more than once, you see the same Java object, meaning that if (for example) you retrieve a User from the UserRepository and then see a Set<User> somewhere else, you have the identical object in both places. In this case, Collection#remove will do what you want.

The MongoDB support is different: It just maps POJOs as passive data objects. This means that unless your entity class implements equals and hashCode, the collection implementations (and anything else) won't consider them equal. You'd need to do something like removeIf based on ID.

(This, by the way, is why you need to call repo.save(changed) with most repository implementations, even though you don't with JPA specifically.)

  • Related