Reputation: 1496
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.
Upvotes: 1
Views: 4883
Reputation: 43
I know this is old question, but still pops up as a first thread in Google search. I had similar issue, however with totally different root cause.
I used @Version annotation from package:
import org.springframework.data.annotation.Version;
where it should have been:
import javax.persistence.Version;
Maybe someone finds this usefull.
Update:
As pointed out by Rasulbek, in newer versions of Spring Boot you might need
import jakarta.persistence.Version;
Upvotes: 4
Reputation: 12734
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 @Version
explicity set.
In your case order
should have a change to get the version updated. (Not the sub-entities)
Upvotes: 2