Sanush Chacko Sanush Chacko - 1 month ago 23
Java Question

Will HQL query use Hibernate Secondary cache

I would like to clarify some points regrading the secondary level cache of hibernate. The point to clarify is, will the HQL queries always hit the database (at least for getting ids).

Consider we have entities

class Customer {

long id; // Primary key

String name;

set <Address> addressList; // One to many relationship

}

class Address{

long id; // Primary key

String houseName;

}


The database table for the Address has a foreign key reference to the Customer (id) to support one to many relationship.

As a precondition, I have enabled the level 2 cache for hibernate as EHcache. Only the entity and associations are set to be cacheable. Query caching is not enabled.

I know that if I use the session.get() or session.load() more than one time, only the first call will fire a query to the databases and subsequent ones will take the data from level 2 cache.

My questions are

1) Will HQL take advantage of the second level cache.
In one session i executed one HQL to get the object using the primary key (id), "from Customer c where c.id = ? ").setParameter(1, 1005).

If I ran the same HQL in a different session, will the Customer object is taken from the level 2 cache or it will hit the database again.

2) Consider another HQL executed "from Customer as c left join fetch c.addressList" for selecting the customer and associated Address.

If i ran the same HQL in a different session, will the associated Address be taken from the level 2 cache or it will hit the database again.

Answer

Because you haven't enabled the query cache, no entity query will hit the 2nd level cache. Therefore, both queries and run against the DB.

You can enable the query cache if you want those queries to use the 2nd level cache instead. Check out this article for more about this topic.