简体   繁体   中英

How to determine that data previously unmarshalled with JAXB was changed?

I only want to marshall the data with JAXB to a file if the previously unmarshalled data has been changed by the user. I know that classes generated by JAXB don't have equals() method. Is there any simple way to determine whether the data has been changed after unmarshalling?

Eg org.w3c.dom.Document has isEqualNode() method for this purpose.

So, JAXB does not produce classes it marshalls data from instances of classes or populates instances by unmarshalling xml. Usually the classes are generated prior to compile-time by XJC. One option is to update the classes to include an equals method. This is not a great idea since you generally don't want to update generated code in case you need to regenerate at a later date. So you could write a utility class that takes two instances of the classes and compares them.

This is for comparing after unmarshalling. Another option would be to perform a check prior to unmarshalling by doing a checksum on the file.

The best is probably to implement Comparator or utility classes to check equality. You could for instance rely on commons-lang EqualsBuilder and CompareToBuilder .

One fairly standard approach is to add a transient boolean to the class, isDirty , and your setter methods will set that to true. (or, if you prefer, add a dateModified )

Obviously, this requires changing your internal class code which may be inappropriate.

You could also keep some Set of all objects that have been modified. But getting this logic correct may also be tricky or impossible depending on how your code is organized.

You can use the JAXB2 Basics Plug-in to have equals methods generated into your model classes:

I have decided to marshal to a org.w3c.dom.Document and to use its isEqualNode()-method. If the original document differs from the new one then I marshal to a file. As I haven't so much XML data it works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM