4

I made some "save" bean functionality in my Java Web Application (JSF1.2, RichFaces). It is using JAXB to turn it into an XML string and then it is stored in the database. If the user loads this back, I want to notify the user if the (bean)content is changed and it should be saved again.

My idea is to override the hashCode() function 'with' org.apache.commons.lang.builder.HashCodeBuilder, however I have lots of fields and child elements. Is there any other way to handle this kind of functionality?

EDIT

"Comparison" is done on another view!

Any help would be appreciated!

Daniel Szalay
  • 4,041
  • 12
  • 57
  • 103
  • 1
    In case you go for an hashCode-based solution, remember to modify your equals() method accordingly. Apart from that I agree that you should add a "modified" flag at the instance level, be sure that all changes go through setter methods, and modify each setter so that if it receives a value which is different from the one already stored in the property it sets the flag. Clear this every time you have written or reread the object. – p.marino Feb 27 '10 at 09:09

3 Answers3

5

You could add a boolean dirty; flag to the bean, set it to true in your setters and clear it during a reload and after a save.

rsp
  • 23,135
  • 6
  • 55
  • 69
  • Well, in your setters and in any other methods that modify any variables in any way. Or make sure that your setters are the only such methods. – Tyler Feb 27 '10 at 09:03
  • Problem is that the user can submit the same values, causing all the setter methods to be called. – Daniel Szalay Feb 27 '10 at 11:51
  • That works if the setter examines whether the value has been changed. Still a lot of redundant code, but works. – Daniel Szalay Feb 27 '10 at 11:58
1

You can't rely on hashCode alone to determine if an object has been changed. That is, just because the object has the same hashCode as before, does NOT mean that it has not been changed.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • But let's say a field that's used in the `hashCode` calculation has been changed. Than I can rely on the object having a different `hashCode` than before, can't I? –  Feb 10 '12 at 09:39
  • @user321068 Not necessarily. A good hash function will make it unlikely for the object to keep the same hash code after being modified, but this is not a strict guarantee. – Ken Wayne VanderLinde Mar 01 '17 at 05:46
  • user321068, the answer above answers your question, doesn't it? The only guarantee is this: if an object has *not* changed, its `hashCode` remains the same. – flow2k Jun 25 '17 at 10:11
-1

You can use Java's MD5 functionality:

MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(myObject);
byte[] hash = digest.digest();
Harun
  • 24
  • 1