hql有如下两个限制:
HQL(SQL)不支持select count(distinct x, y) from xx;
HQL不支持select count(*) from (select distinct x, y from xx);
即:HQL不支持from语句中的子查询。
PS:hql不能在distinct,group by结果集上使用count的问题 !
可以把对hql的查询直接转换成堆sql的操作:
<pre name="code" class="java">String sql = "select count(distinct(order_id)) from t_credit_log where usercode = :usercode and remark like '%" + remark + "%'"; Query query = ht.getSessionFactory().openSession().createSQLQuery(sql) .setParameter("usercode", usercode); List list = query.list(); BigDecimal count = list == null || list.size() <= 0 ? new BigDecimal(0) : (BigDecimal) list.get(0); if (count.intValue() >= 3) { flag = true; }
由于我返回的数据不大,所以直接通过返回一个集合之后取大小也能解决问题,但是结果集大就有效率问题了。
注意:转换成对sql的查询,count返回的结果类型是java.math.BigDecimal,所以如果直接对最后的结果要处理下,转成int类型的。
在网上找的方法,把hql语句转换成sql:
public Long getDataTotal(String hql, Object[] values) { QueryTranslatorImpl queryTranslator = new QueryTranslatorImpl(hql, hql, Collections.EMPTY_MAP, (SessionFactoryImplementor) this .getSessionFactory()); queryTranslator.compile(Collections.EMPTY_MAP, false); String tempSQL = queryTranslator.getSQLString(); String countSQL = "select count(*) from (" + tempSQL + ") tmp_count_t"; Query query = this.getSession().createSQLQuery(countSQL); for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } List list = query.list(); BigDecimal count = list == null || list.size() <= 0 ? new BigDecimal(0) : (BigDecimal) list.get(0); return count.longValue(); }个人感觉有点麻烦,还不如直接写sql执行。