Query Hibernate Cache instead of database

柔情痞子 提交于 2019-12-13 07:03:30

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/20369367/query-hibernate-cache-instead-of-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!