2

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.

4
  • What would be the reason doing that? Testing? Do you want to update the version field in entity itself or only in db? Commented Nov 10, 2017 at 8:04
  • 1
    Basically there are some external entities which are not foreign keys of current entities but use the data from current entity. and in concurrency context, I want to lock the entity without changing its data. Commented Nov 10, 2017 at 10:00
  • I haven't fully understand why you should do this but it sounds like a workaround in a problem you have. Why don't you analyze the problem further instead of implementing in anti-pattern way. If I have understood correctly you might need a dto (data transfer object). Commented Nov 10, 2017 at 15:08
  • Not understanding it does not make it an anti-pattern ;) Commented Dec 2, 2021 at 20:18

2 Answers 2

1

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;
            }
        });
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.