Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Hibernate query to access database

I have loaded an entity into my transaction and have changed a property of that entity. The transaction is not yet commited. Now I would like to get the original value of the changed property.

I've tried with a HQL query like select p.property from Person p where p.id = 1 with the ID of the entity loaded in the transaction.

I've set query.setHint("org.hibernate.cacheMode", CacheMode.IGNORE); before executing the query. But no success. Hibernate returns the value as set in the current transaction, not the one from the database.

Is there any way around this?

like image 772
tobiasbayer Avatar asked Sep 13 '10 13:09

tobiasbayer


1 Answers

I have loaded an entity into my transaction and have changed a property of that entity. The transaction is not yet commited. Now I would like to get the original value of the changed property.

In short: track the old value yourself.

I've tried with a HQL query like select p.property from Person p where p.id = 1 with the ID of the entity loaded in the transaction.

Hibernate loads a unique version of an entity into the session (the first level cache) for a given database identifier. This won't work.

I've set query.setHint("org.hibernate.cacheMode", CacheMode.IGNORE); before executing the query.

This hint is used to affect the query cache (that rely on the second-level-cache), this won't affect your current "issue".

Is there any way around this?

Either

  • use session.refresh() to force a reload of your entity (and you'll loose the changes)
  • store the previous value as initially mentioned.
  • invoke a service that perform a query in another transaction.
like image 140
Pascal Thivent Avatar answered Oct 20 '22 23:10

Pascal Thivent