JPA @Version field doesn't get incremented
The entityManager.persist()
method is meant to be used only for new entities that have never been persisted before.
Because you are fetching an entity you don't need to call persist or merge anyway. The dirty checking will do the update on your behalf.
The commit will trigger the flush anyway so you should see the update.
Make sure you use the javax.persistence.Version
annotation and not from another package (spring data or something similar).
This may not be exactly on topic (as I am using SpringData repositories) but when I was looking for the answer to my problem I ended up here, so this may help the next person.
the following and my version field was not being returned updated.
savedJpa = repository.save(updateJpa);
In the end my solution was
savedJpa = repository.saveAndFlush(updateJpa);
JPA only updates the version only when there really exists some dirty data (uncommitted) present in the entity. I assume Student 195948 already had semester value as "1". Though you are setting the value, which is equal to the previous value, ideally there is no change in the entity state. Hence JPA is not updating the version value. If you set the semester value to different value (not the earlier one), then there is a change in the state of the entity and it updates the version column accordingly.
Thanks, Jagan