我的組對像有一組@DBRef 的用戶,每個用戶同樣有一組@DBRef 的組:
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;
//...
}
當我刪除一個用戶時,我當然必須將他從他的組中刪除:
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);
}
這不起作用。remove(user)
由於某種原因返回 false。它應該可以工作;我打印了每個成員的 ID users
,然後是user.getId()
,然後是結果remove(user)
:
List of users:
61abd6f1c81ab948c31641f2
User to delete: 61abd6f1c81ab948c31641f2
Result of removal: false
您似乎已經習慣了 JPA,它使用各種奇妙的魔法手段來確保(在特定事務中)如果您多次看到相同的數據庫記錄,您會看到相同的 Java 對象,這意味著如果(例如)您User
從 中檢索 aUserRepository
然後在Set<User>
其他地方看到 a ,您在兩個地方都有相同的對象。在這種情況下,Collection#remove
會做你想做的。
MongoDB 支持不同:它只是將 POJO 映射為被動數據對象。這意味著除非您的實體類實現equals
and hashCode
,否則集合實現(和其他任何東西)不會認為它們相等。您需要removeIf
根據 ID執行類似操作。
(順便說一句,這就是為什麼您需要repo.save(changed)
使用大多數存儲庫實現進行調用,即使您沒有專門使用 JPA。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句