简体   繁体   中英

Query Hibernate Cache instead of database

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?

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

Hibernate Caching

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM