[英]Spring with hibernate cache native query
我將Spring 3.2與Hibernate 4結合使用。在我的DAO實現中,我想緩存本機SQL查詢的結果。 獲取此查詢結果的方法如下所示:
public List<Object[]> getBestSellers(String category)
{
Session session = sessionFactory.getCurrentSession();
Query query = session.createSQLQuery( "SELECT i_id, i_title, a_fname, a_lname , SUM(ol_qty) AS val " +
"FROM " +
"orders, order_line, item, author " +
"WHERE " +
"order_line.ol_o_id = orders.o_id AND item.i_id = order_line.ol_i_id " +
"AND item.i_subject = :category AND item.i_a_id = author.a_id GROUP BY i_id " +
"ORDER BY orders.o_date, val DESC" );
query.setParameter( "category", category );
query.setMaxResults( 50 );
query.setCacheable( true );
List<Object[]> res = query.list();
return res;
}
看來那行不通,我也不知道為什么。
我已經在applicationContext.xml中配置了Hibernate,如下所示:
<props>
<prop key="hibernate.jdbc.batch_size">50</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.max_fetch_depth">4</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">classpath:ehcache.xml</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
和我的ehcache.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir/Cloudscale-cache"/>
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU"
/>
<cache
name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxElementsInMemory="50"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="86400"
overflowToDisk="true"/>
<cache
name="org.hibernate.cache.internal.StandardQueryCache"
maxElementsInMemory="50"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="86400"
overflowToDisk="true"/>
</ehcache>
如果要緩存本機SQL查詢,則必須使用addScalar()
通過使用addScalar()
,hibernate將嘗試將sql查詢的結果轉換為單個命名列而不是實體的返回對象。
如下修改您的查詢
Query query = session.createSQLQuery( "SELECT i_id as a, i_title as b, a_fname as c, a_lname as d, SUM(ol_qty) AS val " +
"FROM " +
"orders, order_line, item, author " +
"WHERE " +
"order_line.ol_o_id = orders.o_id AND item.i_id = order_line.ol_i_id " +
"AND item.i_subject = :category AND item.i_a_id = author.a_id GROUP BY i_id " +
"ORDER BY orders.o_date, val DESC" ).addScalar("a").addScalar("b").addScalar("c").addScalar("d").addScalar("val");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.