hibernatejpaspring-boot

@Version not incremented


Here is my simple entity:

import javax.persistence.Version;
@Entity
@Table(name="orders")
public class Order implements Serializable {
    @Version
    @Column(name="version")
    private Long version;

    @Version
    public Long getVersion() {
        return version;
    }
    @Version
    public void setVersion(Long version) {
        this.version = version;
    }
}

I added @Column and @Version to getter and setter because it is not working. The version in the mysql database was initially null and then 0. When I do a

order = em.merge(order);

the version is NOT incremented. Why? I hoped that the version is incremented automatically during merge and to get an javax.persistence.OptimisticLockException when the version does not match. Do I need something like @Lock(LockModeType.OPTIMISTIC_FORCE_INCREMENT)?

Also, what is org.springframework.data.annotation.Version? Should I use that? What does it do?

I am using spring boot 1.5.3.


Solution

  • It is enough to have the @Version annotation on the field. You should also be sure that the entity has really changes. Because if the entity has no changes there will be no update on the version. Also Sub-Entities just get updated if there is @Versionexplicity set.

    In your case order should have a change to get the version updated. (Not the sub-entities)