Reputation: 364
I am new to Hibernate JPA. As I understand the optimistic_force_increment in hibernate jpa: if the entity is updated anywhere in a transaction when updated entity commits, it updates the version field column in database.
Now my question is, is there any way to update the @version field without updating any data inside the entity?
Highly appreciate a code snippet or example to do the same.
Upvotes: 2
Views: 1953
Reputation: 722
Look at this article: https://thorben-janssen.com/hibernate-tips-increase-version-parent-entity-updating-child-entity/
For increasing the version without updating it, the author proposes the following:
TypedQuery q = em.createQuery("SELECT b FROM Book b WHERE b.id = 1", Book.class);
q.setLockMode(LockModeType.OPTIMISTIC_FORCE_INCREMENT);
Book b = q.getSingleResult();
Additionally look at this article, that also deals with this question and proposes how this can be automatically done via event listeners: https://vladmihalcea.com/how-to-increment-the-parent-entity-version-whenever-a-child-entity-gets-modified-with-jpa-and-hibernate/
Upvotes: 0
Reputation: 3212
There is workaround: you could evict and add entity to session, look at this snippet:
public void forceUpdate(Object aEntity) {
getHibernateTemplate().execute(new HibernateCallback<Void>() {
@Override
public Void doInHibernate(Session aSession) throws HibernateException {
if (aSession.contains(aEntity)) {
aSession.evict(aEntity);
}
aSession.update(aEntity);
return null;
}
});
}
Upvotes: 1