论坛首页 Java版 Hibernate

关于DetachedCriteria的一个问题

浏览 350 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
时间:2007-11-30
public PaginationSupport findPageByCriteria(
final DetachedCriteria detachedCriteria, final int pageSize,
final int startIndex) {
return (PaginationSupport) getHibernateTemplate().execute(
new HibernateCallback() {

public Object doInHibernate(Session session)
throws HibernateException, SQLException {
// TODO Auto-generated method stub
Criteria criteria = detachedCriteria
.getExecutableCriteria(session);

CriteriaImpl impl = (CriteriaImpl) criteria;

// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
Projection projection = impl.getProjection();
List<OrderEntry> orderEntries = new ArrayList<OrderEntry>();
try {
Field field = CriteriaImpl.class
.getDeclaredField("orderEntries");
// Get orders
field.setAccessible(true); //is very importance
orderEntries = (List) field.get(impl);
// Remove orders
field.set(criteria, new ArrayList());


} catch (Exception ex) {
ex.printStackTrace();
// TODO
}

int totalCount = ((Integer) criteria.setProjection(
Projections.rowCount()).uniqueResult())
.intValue();
criteria.setProjection(null);
criteria.setResultTransformer(Criteria.ROOT_ENTITY);
try {
Field field = CriteriaImpl.class
.getDeclaredField("orderEntries"); // Add orders return
field.setAccessible(true);
for (int i = 0; i < orderEntries.size(); i++) {
List innerOrderEntries = (List) field
.get(criteria);
innerOrderEntries.add(orderEntries.get(i));
}
} catch (Exception ex) {
ex.printStackTrace();
// TODO cccc
}

List itemLists = criteria.setFirstResult(startIndex)
.setMaxResults(pageSize).list();
/*
* criteria.setFirstResult(0).setMaxResults(totalCount);
* 加上后后次的查询会出现select top totalCount count(*) as y0_ from name this_ inner join address ad1_ on this_.id=ad1_.name_id where ad1_.address=?
* 如何不出现top totalCount?
*/
criteria.setFirstResult(0).setMaxResults(totalCount);
PaginationSupport ps = new PaginationSupport(itemLists,
totalCount, pageSize, startIndex);
return ps;
}
}, true);

}
在第一次查询完毕后执行criteria.setFirstResult(0).setMaxResults(totalCount);
再执行第二次查询totalCount时会出现select top totalCount count(*) as y0_ from name...
虽然不会产生错误,但是这条SQL语句看着总是不爽。请问各位如何处理?谢谢了。
   
论坛首页 Java版 Hibernate

跳转论坛:
JavaEye推荐