i am using both second level cache and query cache. Here is the code snippet
//first block
session = factory.openSession();
company1=(Company)session.get(Company.class, 1);
session.close();
//second block
session = factory.openSession();
tx = session.beginTransaction();
Query updateQuery=session.createQuery("update Company set companyName = 'newCompany' where companyId=1");
updateQuery.setCacheable(true);
updateQuery.executeUpdate();
tx.commit();
session.close();
//Third block
session = factory.openSession();
company1=(Company)session.get(Company.class, 1); // line 1
session.close();
In second block i did update in query . In third block i am getting the company record thru second level cache. What i was expecting i will get the same result(in 3rd block) what i got in first block but i got the updated record (done by query update in 2nd block) i.e "newCompany" at line 1
So looks like query cache and second level cache are in synch with each other as update done by query cache is picked by second level cache.
UPDATE:- So How does query and second level cahe works in synch? I mean does query cache first check under second level cache whether there has been any update for the given query parameter?
The query cache stores IDs returned by previous executions of a cacheable select query.
Let's say you execute the following cacheable query:
select line from OrderLine line join line.order order
where line.status = ? and order.date = ?
If you execute it once, Hibernate will store the IDs of the lines returned by the query in its query cache. And it will store the lines themselves in the second-level cache.
If you execute the same query a second time, with the same parameters, Hibernate will extract the IDs from the query cache, without executing the select query. Then it will get every line by ID (which should be fast since the lines are in the second-level cache)
If you insert, update or delete a line or an order, Hibernate will detect it. Since this modification could affect the result of the cached query, the cache entries associated with this query in the query cache will be evicted. So the nexttime you execute this query again, it will be executed against the database, and the results will be stored again in the query cache.