简体   繁体   English

查询休眠缓存而不是数据库

[英]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. 二级缓存是SessionFactory级别的缓存,因此可以为任何用户缓存结果填充。

AS far as i understand you need cache for a specific query. 据我了解,您需要特定查询的缓存。 Hibernate has also this feature. Hibernate也具有此功能。 org.hibernate.Query.setCacheable(true) can be used here. org.hibernate.Query.setCacheable(true)可以在这里使用。

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). 要为特定查询启用结果缓存,请调用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. session.load()方法将首先检查会话级缓存中的实体。 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. 但是session.get()方法每次都会直接从数据库获取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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