What is the best way to determine if Object has been changed?

南楼画角 提交于 2019-12-21 02:46:39

问题


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!


回答1:


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.




回答2:


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.




回答3:


You can use Java's MD5 functionality:

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


来源:https://stackoverflow.com/questions/2346726/what-is-the-best-way-to-determine-if-object-has-been-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!