在 pom.xml 中添加了以下内容:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
</dependency>
然后,在客户存储库中关注
@Cacheable(cacheNames="customer", key="#email")
@Query(value = "select company_name from customer where email =?1", nativeQuery = true)
List<String> getUserByEmailID(String emailID);
app.prop 文件中给出以下内容:
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.use_query_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.javax.persistence.sharedCache.mode=ALL
在客户实体中添加了以下内容:
@Cacheable
@org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE)
@Table(name = "customer")
public class Customer implements Serializable {
..}
需要缓存的代码:
List<String> ibCustomers = customerRepository.getUserByEmailID("XXX@abc.com");
我的目标是通过查询实现二级缓存,这意味着如果第二次创建相同的查询,则该查询不应执行。现在,尽管我给出了相同的电子邮件,但查询总是被触发,因为我每次都在日志中看到这一点:
org.hibernate.SQL :
/* dynamic native SQL query */ select
company_name
from
customer
where
email =?
我做错了什么?
最佳答案
您可以使用 JPA 缓存(我猜 @Cacheable
与 JPA 相关)或 Hibernate 缓存,因此您应该考虑 2 个场景。
JPA场景
对于 JPA:根据 JPA 规范,为了启用 JPA 缓存(@Cacheable
是 JPA 注释吗?),您必须指定 <shared-cache-mode>
在你的persistence.xml
例如:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="SimpleTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
</properties>
</persistence-unit>
</persistence>
hibernate 场景
如果您使用 hibernate 缓存,则必须使用 @Cache
Hibernate 提供的注释 ( Hibernate @Cache )
此外,如果您使用 hibernate Query 对象,则必须指定应通过执行以下操作来缓存查询:
Query q = hibSession.createQuery(....);
q.setCacheable(true);
您可以在这里找到更多信息 https://www.baeldung.com/hibernate-second-level-cache
我希望这有用
关于java - 二级缓存 + Spring Boot + Java Hibernate 中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54234051/