-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Should PersistentSet.add(...) always mark the Set as dirty?
PostPosted: Mon Oct 24, 2005 10:47 am 
Newbie

Joined: Thu Jul 07, 2005 8:10 am
Posts: 6
Location: St. Louis, MO
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.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.