Native queries are clearing the 2nd level cache entries. An answer from the hibernate forum that is 7 years old says that HQL update queries also clear the 2nd level cache.
Native queries are clearing the 2nd level cache entries.
There is though a possibility to specify what from 2nd level cache should be invalidated (or even specify that nothing is evicted from cache). Look at great blog post http://www.link-intersystems.com/bin/view/Blog/Hibernate%27s+second+level+cache+and+native+queries where this is explained thoroughly.
To prevent Hibernate from invalidating anything from cache:
SQLQuery sqlQuery = session.createSQLQuery("ALTER SESSION SET NLS_COMP = 'BINARY'");
sqlQuery.addSynchronizedQuerySpace("");
int updatedEntities = sqlQuery.executeUpdate();
To instruct Hibernate to invalidate only the Person entity cache:
SQLQuery sqlQuery = session.createSQLQuery("UPDATE PERSON SET ... WHERE ...");
sqlQuery.addSynchronizedEntityClass(Person.class);
int updatedEntities = sqlQuery.executeUpdate();
An answer from the hibernate forum that is 7 years old says that HQL update queries also clear the 2nd level cache. But is this still true?
Example:
entityManager.createQuery("delete from Person p where p.id = 1").executeUpdate();
This will invalidate "only" the Person entity cache.
I am not aware of any possibility to prevent Hibernate from invalidating 2nd level cache for specific entity when it comes to HQL.
The closest thing I could dig up was this: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html#performance-cache
I would imagine it has a lot to do with which provider you use.
We did see HQL update clearing the 2nd level cache when running with Hibernate 3.2.x
As a simple way to validate for your individual setup, implement something like:
http://narcanti.keyboardsamurais.de/hibernate-statistics-jsp-reloaded.html
Note details on that page before and after running the HQL update transaction ...
Or gather stats directly in your code and/or using JMX
http://docs.jboss.org/hibernate/core/3.5/reference/en/html/performance.html#performance-monitoring
As for improved behaviour, the Hibernate project might be open to implement a patch :)