EhCache + hibernate

dan*_*nik 6 java spring hibernate ehcache second-level-cache

我有以下问题:我有一个查询,它返回35我的结果,我想保持在二级缓存:

public List<Product> getAllProducts() {
        Session session = this.sessionfactory.getCurrentSession();
        String queryString = "from com.ewave.upromotions.objects.Product product where product.active=:active";
        Query query = session.createQuery(queryString); 
        query.setBoolean("active", true);
        query.setCacheable(true);
        query.setCacheRegion("productCache");
        List<Product> products =query.list();
        return products;
    }
Run Code Online (Sandbox Code Playgroud)

我的目标如下:

@Entity
@Table(name="products",schema="test11")
@Cacheable
@Cache( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Product implements Serializable {

//all setters and getters ommited:

}
Run Code Online (Sandbox Code Playgroud)

我的ehcache.xml文件位于/ src /目录中:

<ehcache>  
    <diskStore path="java.io.tmpdir"/>  
    <defaultCache maxElementsInMemory="10000"  
        eternal="false"  
        timeToIdleSeconds="120"  
        timeToLiveSeconds="120"  
        overflowToDisk="false"/>  
    <cache name="hibernate.test.org.hibernate.cache.UpdateTimestampsCache"   
        maxElementsInMemory="10000"  
        eternal="false"  
        timeToIdleSeconds="120"  
        timeToLiveSeconds="120"  
        overflowToDisk="true"/>  
    <cache name="hibernate.test.org.hibernate.cache.StandardQueryCache"   
        maxElementsInMemory="10000"  
        eternal="false"  
        timeToIdleSeconds="120"  
        timeToLiveSeconds="120"  
        overflowToDisk="true"/>
     <cache name="com.vanilla.objects.Product"
        maxElementsInMemory="300"
        eternal="false"
        overflowToDisk="false"
        timeToIdleSeconds="600"  
        timeToLiveSeconds="600"  
        />  
       <cache name="productCache" 
       maxElementsInMemory="100" 
       eternal="true" 
       overflowToDisk="false" />

</ehcache>  
Run Code Online (Sandbox Code Playgroud)

我的Hibernate配置是:

<props>
    <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> 
    <prop key="hibernate.cache.use_second_level_cache">true</prop> 
     <prop key="hibernate.show_sql">true</prop> 
  <prop key="hibernate.cache.use_query_cache">true</prop> 
  <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
  <prop key="hibernate.connection.release_mode">after_transaction</prop>
  <prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>
  </props>
Run Code Online (Sandbox Code Playgroud)

我的问题如下:第一次带页面时,我看到选择带来了所有35个结果:

当我刷新页面时,不是从缓存中带来35个对象,而是看到35个select语句,它们逐个id地查询对象.

怎么了?

Ale*_*man 5

当查询被缓存但对象不是时,它发生在我身上.在您的示例代码中,我看到该查询引用com.ewave.upromotions.objects.Product但您已为其定义了缓存区域com.vanilla.objects.Product.并且您没有为Product类提供任何缓存区域.所以我建议你明确指定缓存区域Product并在缓存配置中定义它.首先,我会为查询和对象尝试相同的区域,只是为了查看它是否有效,然后尝试单独的配置.