Reputation: 23352
I have a query like:
Select * FROM table1 WHERE name LIKE 's%';
I don't want this query to fetch data from database; instead it should return data from hibernate session or something else. I think enabling second level cache will help but not sure that it will help in filtered queries.
How can I force a query not to fetch data from database?
Upvotes: 0
Views: 1896
Reputation: 5700
session.load()
method will check the entity in session level cache first. If it found, then the entity will be returned from cache else it will query the database and return it to the client. But the session.get()
method will directly fetch from database every time.
Upvotes: 0
Reputation: 3763
Hibernate first level cache is Session level cache, so if the object is currently in the Hibernate session results will be fetched from it.
Second level cache is a SessionFactory level cache, so the result fill be cached for any user.
AS far as i understand you need cache for a specific query. Hibernate has also this feature. org.hibernate.Query.setCacheable(true)
can be used here.
From the documentation
Enable results caching for specific queries
Since most queries do not benefit from caching of their results, you need to enable caching for individual queries, e ven after enabling query caching overall. To enable results caching for a particular query, call org.hibernate.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.
See also
Upvotes: 3