DAO类:
public Double getMonthAllPays() throws Exception{
1. 准备hql语句
String hql="String hql = "select sum(d.donations) from DwhDonationMonthly d where d.theYear=:theYear and d.theMonth=:theMonth";
2.定义Map集合,封装参数
Map<String,Object> params = new HashMap<String,Object>();
3.将参数封装进Map集合
Calendar cal = Calendar.getInstance();
params.put("theYear", cal.get(Calendar.YEAR));
params.put("theMonth", cal.get(Calendar.MONTH )+1);
4.将hql语句和参数Map集合传递给hibernate处理
Object obj = super.findObjectByHql(hql, params);
return (Double) (obj == null ? 0 : (Double) obj);
}
findObjectByHql实现:
public Object findObjectByHql(String hql,Map parmas){
Query query = this.hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql);
query = setParams(params, query);
1.query.uniqueResult()只返回一个实例
return query.uniqueResult();
}
setParams(Map params,Query query)的实现:
private Query setParams(Map queryParams, Query query) {
if (queryParams != null && !queryParams.isEmpty()) {
Set set = queryParams.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
String key = it.next().toString();
Object value=queryParams.get(key);
if(value instanceof Collection)
query.setParameterList(key, (Collection) value);
else if(value instanceof Object[])
query.setParameterList(key, (Object[])value);
else
query.setParameter(key,value);
}
}
return query;
}