Are the original SQL queries cached by default when the Hibernate query cache is enabled?

Using Hibernate 3.3.0 and ehcache 1.2.3 with level 2 caching and a query cache, I realized that the following code returned the same sequence number for multiple calls, which caused the insert to fail.

HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { StringBuilder strQuery = new StringBuilder(); strQuery.append("SELECT "); strQuery.append(sequenceName); strQuery.append(".nextval as nextSequence FROM dual d"); Query query = session.createSQLQuery(strQuery.toString()).addScalar("nextSequence", Hibernate.STRING); return query.uniqueResult(); } }; return this.hibernateTemplate.execute(callback).toString(); 

The code works correctly if I turn off the query cache or add the following line before executing the request.

 query.setCacheable(false); 

This is confusing as the hibernate docs clearly state

Most requests do not use caching, so requests are not cached by default. To enable caching, call Query.setCacheable (true). This call allows the query to search for existing caches or add its results to the cache when it is running.

In this case, this is abnormal behavior, and can I assume that requests are not cached by default?

+8
caching hibernate ehcache
source share
1 answer

The query cache is a very simple mechanism that stores the results for a specific key. In the case of your own request, this key will be your request and all parameters.

So, for example, the key could be:

 *----------------------------------------------------------------------------------------* | Query Cache | |----------------------------------------------------------------------------------------| | ["select * from table as t where t.id=? and p.column=?", [ 1 , "value"] ] -> [ 2 ] ] | *----------------------------------------------------------------------------------------* 

From this point of view, each request can be cached - in certain scenarios. Of course, the request should be handled by Hibernate classes, and not directly through a JDBC connection.

And, BTW, it's easy to find out if your request will use the request cache or not! All this in the log files under org.hibernate.cache .

And there’s a big catch in all this - if you run your own request, it will supplant all entities and entries of the second level cache! At least that was until the last version I used! This way you can use your own queries, but since Hibernate cannot decide what they are doing, it will clear the cache to avoid changes to the data made by this query that are not reflected in the cache objects.

As such, there are many problems with the query cache, and you should consider whether you want to use this feature! Look at this article or this one . I try to avoid using query caches in my work, I use only SLC for objects ...

+4
source share

All Articles