hibernate求和使用的是
createSQLQuery方法,用以执行sql语句。这里面具体hibernate相关session等操作这里不介绍了,不懂看前面文章。
service层,执行相应sql语句:
StringBuffer sb=new StringBuffer();
sb.append("SELECT SUM(u.userAnswerScore) FROM t_user_answer u WHERE u.userId=:userId and u.questionnaireId=:questionnaireId" );
Map<String, Object> map=new HashMap<String, Object>();
map.put("userId",userId);
map.put("questionnaireId",questionnaireId);
int count=userAnswerDao.executeSqlHql(sb.toString(), map);
return count;
//在hibernate具体sql操作dao处执行sql:
public int executeSqlHql(String hql, Map<String, Object> params) {
Query q = this.getCurrentSession().createSQLQuery(hql);
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
if(params.get(key) instanceof Object[])
q.setParameterList(key, (Object[])params.get(key));
else if(params.get(key) instanceof Object)
q.setParameter(key, params.get(key));
}
}
List<String[]> sum=q.list();
//获取返回的第一个值,即查询的和
String object=String.valueOf(sum.get(0));
int Int=(int) Double.parseDouble(object);
//注意类型转换
return Int;
}