Hibernate中带distinct的hql分页查询
March 30, 2011 | 0 comments
带distinct的hql查询分页时,不能使用select count(*) from (hql) 这样的方式,这样获得的总数是不对的。
这里的做法是分离出hql的select dinstinc和from之间的部分,变成 select count(distinct … ) from…
代码如下:
/**
* select dinstinct 查询的总数
* 这里按 select count(distinct … ) from … 获得总数.
*
* @param hql
* @param values
* @return
*/
private long getSelectDistinctCount( String hql , Object … values) {
int distinctIndex = hql . toLowerCase (). indexOf( "distinct");
int fromIndex = hql . toLowerCase (). indexOf( "from");
hql = removeOrders( hql);
String countQueryString = " select count(" + hql . substring( distinctIndex , fromIndex) + ") " + hql . substring( fromIndex);
List countlist = this . find( countQueryString , values);
long totalCount = ( Long) countlist . get( 0);
* select dinstinct 查询的总数
* 这里按 select count(distinct … ) from … 获得总数.
*
* @param hql
* @param values
* @return
*/
private long getSelectDistinctCount( String hql , Object … values) {
int distinctIndex = hql . toLowerCase (). indexOf( "distinct");
int fromIndex = hql . toLowerCase (). indexOf( "from");
hql = removeOrders( hql);
String countQueryString = " select count(" + hql . substring( distinctIndex , fromIndex) + ") " + hql . substring( fromIndex);
List countlist = this . find( countQueryString , values);
long totalCount = ( Long) countlist . get( 0);
if (totalCount < 1) {
return 0;
} else
return totalCount;
}