woyaru
woyaru

Reputation: 5634

How to load and update entity to increment Hibernate @Version attribute?

I would like to update @Version attribute of my entity without any changes in entity. This entity has as a child collections of another entity. And I would like to update the basic entity with @Version attribute to get new value of this entity version under Hibernate control. I have something like that (attribute isn't attribute with @Version annotation):

MyEntity entity = (MyEntity) getSession().load(Entity.class, id);
entity.setAttribute(new String(entity.getAttribute()));
getSession().update(entity);

But this is not working. The entiy has new version value only in case I am setting new value to one of its attributes. How can I load and update entity to increment Hibernate @Version attribute without any changes in that case?

Upvotes: 1

Views: 1495

Answers (1)

dcernahoschi
dcernahoschi

Reputation: 15250

In fact you should have a version increment by doing a locking om your entity with a LockMode.FORCE:

Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyEntity u = (MyEntity) session.get(MyEntity.class, id);
session.lock(u, LockMode.FORCE);
tx.commit();
session.close();

Upvotes: 1

Related Questions