问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/24342174/will-hql-query-use-hibernate-second-level-cache