Using Hibernate 3.3.0 and ehcache 1.2.3 with 2nd level caching and query cache turned on, I realised that the following code was returning the same sequence number across multiple calls which resulted in insertion failure.
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 properly if I turn off the query cache or add the following line before executing the query.
query.setCacheable(false);
This is confusing, since Hibernate docs clearly state
Most queries do not benefit from caching, so by default queries are not cached. To enable caching, call Query.setCacheable(true). This call allows the query to look for existing cache results or add its results to the cache when it is executed.
In this case, is this abnormal behavior and can I still make the assumption that queries are not cached by default?