1. 程式人生 > >ssh專案中使用二級快取

ssh專案中使用二級快取

Hibernate中的二級快取, 即繫結在SessionFactory上的快取:


專案新增二級快取
1、需要引入三個jar包
在hibernate下能找到
hibernate-distribution-3.5.6-Final\lib\optional\ehcache\ehcache-1.5.0.jar
在srping下能找到
..\lib\concurrent\backport-util-concurrent.jar
..\lib\jakarta-commons\commons-logging.jar
2、在hibernate.cfg.xml中配置
   (1)開啟二級快取:
        <!-- 開啟二級快取 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 配置二級快取的供應商 -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- 啟動二級快取的查詢快取 -->
<property name="hibernate.cache.use_query_cache">true</property>
   (2)新增類級別的二級快取:
        <!-- 配置類級別的二級快取 -->
<class-cache class="cn.itcast.elec.domain.ElecSystemDDL" usage="read-write"/>
3、測試二級快取:
   在junit包下進行測試,TestHibernateCache.java進行測試:
    public class TestHibernateCache {
@Test
public void testCache(){
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sf = configuration.buildSessionFactory();
Session s = sf.openSession();
Transaction tr = s.beginTransaction();

Query query = s.createQuery("from ElecSystemDDL");
//使用查詢快取
query.setCacheable(true);
query.list();//產生select語句

tr.commit();
s.close();
////////////////////////////////////////////////////////////////////
s = sf.openSession();
tr = s.beginTransaction();

Query query1 = s.createQuery("from ElecSystemDDL");
//使用查詢快取
query1.setCacheable(true);
query1.list();//?

tr.commit();
s.close();

}
}
4、在專案中新增二級快取:
    在CommonDaoImpl中新增方法
  /**使用二級快取,提高系統的檢索效能*/
public List<T> findCollectionByConditionNoPageWithCache(String condition,
final Object[] params, LinkedHashMap<String, String> orderby) {
/**
*  SELECT * FROM elec_text o WHERE 1=1   #DAO層封裝
AND o.textName LIKE ? #Service層封裝
AND o.textRemark LIKE ? #Service層封裝
ORDER BY o.textDate ASC,o.textName DESC #Service層封裝
*/
//定義Hql語句
String hql = "from " + entityClass.getSimpleName() + " o where 1=1";
String orderHql = this.orderByHql(orderby);
final String finalHql = hql + condition + orderHql;
//執行hql語句
//方法一:
//List<T> list = this.getHibernateTemplate().find(hql,params);
//方法二:
List<T> list = (List<T>) this.getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(finalHql);
for(int i=0;params!=null && i<params.length;i++){
query.setParameter(i, params[i]);
}
//啟用二級快取儲存資料
query.setCacheable(true);
return query.list();
}
});
return list;
}