//假设有如下hql
String hql = "select distinct u.sex, u.age from User u where u.id > 10";
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();
}
hql有如下两个限制:
HQL(SQL)不支持select count(distinct x, y) from xx;
HQL不支持select count(*) from (select distinct x, y from xx);
即:HQL不支持from语句中的子查询
转自:http://www.iteye.com/problems/2760