3

I would like to clarify some points regarding 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.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Sanush Chacko
  • 91
  • 1
  • 8

1 Answers1

5

Because you haven't enabled the Query Cache, no entity query (JPQL or Criteria API) will use the 2nd-level cache. Therefore, both queries will be executed against the database.

You can enable the query cache if you want those queries to use the 2nd-level cache instead.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • Thanks @VlanMihalcea. For the question 1, i believe the hibernate will run the query and get id of all the table rows which matches the search criteria. Then it will load the object using the id. The object can be loaded from the level 2 or from the DB as per availability. Isn't strange that here i am only searching by ID, but still it need to go to the DB to fetch the same ID again. – Sanush Chacko Jun 21 '14 at 14:02
  • 1
    The searching by id is a way to override the default fetching mechanism so you can explicitly declare a new fetching plan, and also a query can trigger a flush prior to executing it, so that's why it doesn't simply ignore all those to return the Entity from 1st or 2nd level cache. – Vlad Mihalcea Jun 21 '14 at 15:05
  • Please find the similar thread [link](http://stackoverflow.com/questions/8989584/does-hql-query-always-hit-database-and-get-results) – Sanush Chacko Jun 27 '14 at 16:15