0

I am using JPA and @Version attribute for a Database Entity Object.

The fact is that I have a field "ENTITY_VERSION" at DB mapped to @Version, but also i have this ENTITY_VERSION in a xml representing all the object in a blob type.

The @Version value is self-created right after the record persisted : So, the xml will always be dirty ....

For example:

  1. First Save the xml object "x" (entity is saved with version 1, for example)
  2. Persist the object "x" (Version -ENTITY_VERSION - automatically is put 2).
  3. In the table object x will have the ENTITY_VERSION field to 2, but for the xml to "1"

I tried to update the xml using @PrePersist, getting the value of @Version , but always the value is the old one.

Is anyway to get the @Version value before persist??

Community
  • 1
  • 1
Azimuts
  • 1,212
  • 4
  • 16
  • 35
  • Could you be more descriptive about your use case? Do you persist same information in the db table and in xml (somewhere?)? – zbig Dec 31 '14 at 10:35
  • 1
    In your case version will always be +1 compared to current db value prior to update (of course, if nothing goes wrong during update). But, do you really need version attribute to be marshaled to XML? It's not a business field, and if you want to keep track of changes there are other mechanisms for that. – Predrag Maric Dec 31 '14 at 11:01
  • @PredragMaric hits the nail on the head. The version field is tied to the DB. Exporting it does not make sense. – Stijn de Witt Feb 20 '17 at 08:25

1 Answers1

2

The @Version field is only incremented after successful transaction commit. That is by design. But it is incremented.

You can know for sure that the only way for your transaction to succeed is for @Version field to be the same in the database and in your entity at the time of transaction commit. Because of that, and the fact that version will be incremented, you also know exactly what value it will have after successful commit (X+1). That is the value you should put into your xml to begin with.

Know however, that if transaction rolls back, your xml will be dirty also.

miljanm
  • 906
  • 7
  • 20
  • Thank you, but after a rollback , the xml (is stored in a db) , will be rolled back too, so i think there will be no problem. Yes, i think the best way will be to set xml fiel to X+1..... – Azimuts Dec 31 '14 at 12:27