且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查询Hibernate缓存而不是数据库

更新时间:2022-11-25 13:27:39

Hibernate的第一级缓存是Session级缓存,所以如果对象目前在Hibernate会话结果中将会从中获取结果。 p>

二级缓存是一个SessionFactory级缓存,因此可以为任何用户缓存结果。



只要我知道你需要缓存一个特定的查询。休眠也有这个功能。 org.hibernate.Query.setCacheable(true)可以在这里使用。



从文档


$ b

为特定查询启用结果缓存



而不是
从缓存结果中受益,则需要在启用查询缓存整体后为
个别查询启用缓存。要
为特定查询启用结果缓存,请调用
org.hibernate.Query.setCacheable(true)。这个调用允许查询
查找现有的缓存结果,或者在
执行时将其结果添加到缓存中。


另见

Hibernate缓存


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