Hibernate中带distinct的hql分页查询

Hibernate中带distinct的hql分页查询

  | 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  = ( Longcountlist . get( 0);

 

    if (totalCount < 1{
         return 0;
    } else 
        return totalCount;
}

猜你喜欢

转载自zzhangyx.iteye.com/blog/1717233