Hibernate version: 3.0.5
Synopsis: Should the PersistentSet class mark itself as dirty after you call add(...) with an element that already exists in the Set?
Suppose I have a persistent class called User that contains a Set of Role objects. In the User I have a helper method for adding Roles. This helper method helps ensure the bidirectional association. For example:
Code:
public class User {
private Set roles = new HashSet();
...
public void addRole(Role role) {
// calling add() should not modify the Set if role is a duplicate
if (roles.add(role)) {
role.addUser(this);
}
}
}
If the Role is already in the Set, add(...) returns false and the collection should remain unchanged.
Looking at the source for PersistentSet, it is clear why the dirty flag is set:
Code:
public boolean add(Object value) {
write(); // sets the dirty flag
return set.add(value);
}
I can avoid setting the dirty flag by modifying my code:
Code:
public void addRole(Role role) {
if (!roles.contains(role)) {
roles.add(role);
role.addUser(this);
}
Although this is not quite as concise, it does avoid setting the dirty flag. I don't know what the overall performance impact is...for my very small database it is negligable. But perhaps setting the dirty flag is more of a problem for bigger collections?
So in summary, should Hibernate's PersistentSet set the dirty flag if you call add(...) but the Set already contains the object?
Perhaps PersistentSet should do something like this:
Code:
public boolean add(Object value) {
if (!contains(value)) {
write();
return set.add(value);
}
}
Thanks for any insights.