`

应用Hibernate3的DetachedCriteria实现分页查询

阅读更多
Hibernate3提供了DetachedCriteria,使得我们可以在Web层构造detachedCriteria,然后调用业务层Bean,进行动态条件查询,根据这一功能,我设计了通用的抽象Bean基类和分页类支持,代码来自于Quake Wang的javaeye-core包的相应类,然后又做了很多修改。

分页支持类:

Java代码 复制代码
    package com.iteye.common.util;   
      
    import java.util.List;   
      
    public class PaginationSupport {   
      
        public final static int PAGESIZE = 30;   
      
        private int pageSize = PAGESIZE;   
     
       private List items;   
     
       private int totalCount;   
     
       private int[] indexes = new int[0];   
    
      private int startIndex = 0;   
     
      public PaginationSupport(List items, int totalCount) {   
          setPageSize(PAGESIZE);   
                   setTotalCount(totalCount);   
          setItems(items);           
           setStartIndex(0);   
       }   
     
       public PaginationSupport(List items, int totalCount, int startIndex) {   
                   setPageSize(PAGESIZE);   
           setTotalCount(totalCount);   
           setItems(items);           
           setStartIndex(startIndex);   
       }   
     
       public PaginationSupport(List items, int totalCount, int pageSize, int startIndex) {   
                   setPageSize(pageSize);   
           setTotalCount(totalCount);   
           setItems(items);   
           setStartIndex(startIndex);   
       }   
     
       public List getItems() {   
           return items;   
       }   
     
       public void setItems(List items) {   
           this.items = items;   
        }   
     
       public int getPageSize() {   
           return pageSize;   
       }   
     
       public void setPageSize(int pageSize) {   
           this.pageSize = pageSize;   
       }   
     
       public int getTotalCount() {   
           return totalCount;   
       }   
     
       public void setTotalCount(int totalCount) {   
           if (totalCount > 0) {   
               this.totalCount = totalCount;   
               int count = totalCount / pageSize;   
               if (totalCount % pageSize > 0)   
                   count++;   
               indexes = new int[count];   
               for (int i = 0; i < count; i++) {   
                   indexes[i] = pageSize * i;   
               }   
           } else {   
               this.totalCount = 0;   
           }   
      }   
     
      public int[] getIndexes() {   
           return indexes;   
       }   
    
       public void setIndexes(int[] indexes) {   
           this.indexes = indexes;   
       }   
     
       public int getStartIndex() {   
           return startIndex;   
       }   
     
       public void setStartIndex(int startIndex) {   
           if (totalCount <= 0)   
               this.startIndex = 0;   
           else if (startIndex >= totalCount)   
               this.startIndex = indexes[indexes.length - 1];   
           else if (startIndex < 0)   
              this.startIndex = 0;   
           else {   
               this.startIndex = indexes[startIndex / pageSize];   
           }   
       }   
     
       public int getNextIndex() {   
          int nextIndex = getStartIndex() + pageSize;   
          if (nextIndex >= totalCount)   
              return getStartIndex();   
          else  
              return nextIndex;   
      }   
    
      public int getPreviousIndex() {   
          int previousIndex = getStartIndex() - pageSize;   
          if (previousIndex < 0)   
              return 0;   
          else  
              return previousIndex;   
      }   
    
  }  

package com.iteye.common.util;

import java.util.List;

public class PaginationSupport {

 public final static int PAGESIZE = 30;

 private int pageSize = PAGESIZE;

 private List items;

 private int totalCount;

 private int[] indexes = new int[0];

 private int startIndex = 0;

 public PaginationSupport(List items, int totalCount) {
  setPageSize(PAGESIZE);
                setTotalCount(totalCount);
  setItems(items);  
  setStartIndex(0);
 }

 public PaginationSupport(List items, int totalCount, int startIndex) {
                setPageSize(PAGESIZE);
  setTotalCount(totalCount);
  setItems(items);  
  setStartIndex(startIndex);
 }

 public PaginationSupport(List items, int totalCount, int pageSize, int startIndex) {
                setPageSize(pageSize);
  setTotalCount(totalCount);
  setItems(items);
  setStartIndex(startIndex);
 }

 public List getItems() {
  return items;
 }

 public void setItems(List items) {
  this.items = items;
 }

 public int getPageSize() {
  return pageSize;
 }

 public void setPageSize(int pageSize) {
  this.pageSize = pageSize;
 }

 public int getTotalCount() {
  return totalCount;
 }

 public void setTotalCount(int totalCount) {
  if (totalCount > 0) {
   this.totalCount = totalCount;
   int count = totalCount / pageSize;
   if (totalCount % pageSize > 0)
    count++;
   indexes = new int[count];
   for (int i = 0; i < count; i++) {
    indexes[i] = pageSize * i;
   }
  } else {
   this.totalCount = 0;
  }
 }

 public int[] getIndexes() {
  return indexes;
 }

 public void setIndexes(int[] indexes) {
  this.indexes = indexes;
 }

 public int getStartIndex() {
  return startIndex;
 }

 public void setStartIndex(int startIndex) {
  if (totalCount <= 0)
   this.startIndex = 0;
  else if (startIndex >= totalCount)
   this.startIndex = indexes[indexes.length - 1];
  else if (startIndex < 0)
   this.startIndex = 0;
  else {
   this.startIndex = indexes[startIndex / pageSize];
  }
 }

 public int getNextIndex() {
  int nextIndex = getStartIndex() + pageSize;
  if (nextIndex >= totalCount)
   return getStartIndex();
  else
   return nextIndex;
 }

 public int getPreviousIndex() {
  int previousIndex = getStartIndex() - pageSize;
  if (previousIndex < 0)
   return 0;
  else
   return previousIndex;
 }

}




抽象业务类
Java代码 复制代码

   1. /**  
     * Created on 2005-7-12  
     */  
    package com.iteye.common.business;   
      
    import java.io.Serializable;   
    import java.util.List;   
      
    import org.hibernate.Criteria;   
    import org.hibernate.HibernateException;   
    import org.hibernate.Session;   
   import org.hibernate.criterion.DetachedCriteria;   
   import org.hibernate.criterion.Projections;   
   import org.springframework.orm.hibernate3.HibernateCallback;   
   import org.springframework.orm.hibernate3.support.HibernateDaoSupport;   
     
   import com.iteye.common.util.PaginationSupport;   
    
   public abstract class AbstractManager extends HibernateDaoSupport {   
     
       private boolean cacheQueries = false;   
     
       private String queryCacheRegion;   
     
       public void setCacheQueries(boolean cacheQueries) {   
           this.cacheQueries = cacheQueries;   
       }   
     
       public void setQueryCacheRegion(String queryCacheRegion) {   
           this.queryCacheRegion = queryCacheRegion;   
       }   
     
       public void save(final Object entity) {   
          getHibernateTemplate().save(entity);   
       }   
     
       public void persist(final Object entity) {   
           getHibernateTemplate().save(entity);   
       }   
     
       public void update(final Object entity) {   
           getHibernateTemplate().update(entity);   
       }   
     
       public void delete(final Object entity) {   
           getHibernateTemplate().delete(entity);   
       }   
     
       public Object load(final Class entity, final Serializable id) {   
           return getHibernateTemplate().load(entity, id);   
       }   
     
       public Object get(final Class entity, final Serializable id) {   
           return getHibernateTemplate().get(entity, id);   
       }   
     
       public List findAll(final Class entity) {   
           return getHibernateTemplate().find("from " + entity.getName());   
       }   
     
       public List findByNamedQuery(final String namedQuery) {   
           return getHibernateTemplate().findByNamedQuery(namedQuery);   
       }   
     
       public List findByNamedQuery(final String query, final Object parameter) {   
           return getHibernateTemplate().findByNamedQuery(query, parameter);   
       }   
     
       public List findByNamedQuery(final String query, final Object[] parameters) {   
           return getHibernateTemplate().findByNamedQuery(query, parameters);   
       }   
     
       public List find(final String query) {   
          return getHibernateTemplate().find(query);   
       }   
     
       public List find(final String query, final Object parameter) {   
           return getHibernateTemplate().find(query, parameter);   
      }   
   
     public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria) {   
         return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, 0);   
    }   
  
     public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria, final int startIndex) {   
         return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, startIndex);   
     }   

     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 {   
                 Criteria criteria = detachedCriteria.getExecutableCriteria(session);   
                 int totalCount = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();   
                criteria.setProjection(null);   
                 List items = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();   
                 PaginationSupport ps = new PaginationSupport(items, totalCount, pageSize, startIndex);   
                 return ps;   
            }   
         }, true);   
     }   
   
     public List findAllByCriteria(final DetachedCriteria detachedCriteria) {   
         return (List) getHibernateTemplate().execute(new HibernateCallback() {   
            public Object doInHibernate(Session session) throws HibernateException {   
                 Criteria criteria = detachedCriteria.getExecutableCriteria(session);   
                 return criteria.list();   
              }   
         }, true);   
      }   
    
      public int getCountByCriteria(final DetachedCriteria detachedCriteria) {   
          Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback() {   
              public Object doInHibernate(Session session) throws HibernateException {   
                 Criteria criteria = detachedCriteria.getExecutableCriteria(session);   
                  return criteria.setProjection(Projections.rowCount()).uniqueResult();   
             }   
          }, true);   
         return count.intValue();   
      }   
  }  

/**
 * Created on 2005-7-12
 */
package com.iteye.common.business;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.iteye.common.util.PaginationSupport;

public abstract class AbstractManager extends HibernateDaoSupport {

 private boolean cacheQueries = false;

 private String queryCacheRegion;

 public void setCacheQueries(boolean cacheQueries) {
  this.cacheQueries = cacheQueries;
 }

 public void setQueryCacheRegion(String queryCacheRegion) {
  this.queryCacheRegion = queryCacheRegion;
 }

 public void save(final Object entity) {
  getHibernateTemplate().save(entity);
 }

 public void persist(final Object entity) {
  getHibernateTemplate().save(entity);
 }

 public void update(final Object entity) {
  getHibernateTemplate().update(entity);
 }

 public void delete(final Object entity) {
  getHibernateTemplate().delete(entity);
 }

 public Object load(final Class entity, final Serializable id) {
  return getHibernateTemplate().load(entity, id);
 }

 public Object get(final Class entity, final Serializable id) {
  return getHibernateTemplate().get(entity, id);
 }

 public List findAll(final Class entity) {
  return getHibernateTemplate().find("from " + entity.getName());
 }

 public List findByNamedQuery(final String namedQuery) {
  return getHibernateTemplate().findByNamedQuery(namedQuery);
 }

 public List findByNamedQuery(final String query, final Object parameter) {
  return getHibernateTemplate().findByNamedQuery(query, parameter);
 }

 public List findByNamedQuery(final String query, final Object[] parameters) {
  return getHibernateTemplate().findByNamedQuery(query, parameters);
 }

 public List find(final String query) {
  return getHibernateTemplate().find(query);
 }

 public List find(final String query, final Object parameter) {
  return getHibernateTemplate().find(query, parameter);
 }

 public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria) {
  return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, 0);
 }

 public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria, final int startIndex) {
  return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, startIndex);
 }

 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 {
    Criteria criteria = detachedCriteria.getExecutableCriteria(session);
    int totalCount = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
    criteria.setProjection(null);
    List items = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();
    PaginationSupport ps = new PaginationSupport(items, totalCount, pageSize, startIndex);
    return ps;
   }
  }, true);
 }

 public List findAllByCriteria(final DetachedCriteria detachedCriteria) {
  return (List) getHibernateTemplate().execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Criteria criteria = detachedCriteria.getExecutableCriteria(session);
    return criteria.list();
   }
  }, true);
 }

 public int getCountByCriteria(final DetachedCriteria detachedCriteria) {
  Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Criteria criteria = detachedCriteria.getExecutableCriteria(session);
    return criteria.setProjection(Projections.rowCount()).uniqueResult();
   }
  }, true);
  return count.intValue();
 }
}




用户在web层构造查询条件detachedCriteria,和可选的startIndex,调用业务bean的相应findByCriteria方法,返回一个PaginationSupport的实例ps。

ps.getItems()得到已分页好的结果集
ps.getIndexes()得到分页索引的数组
ps.getTotalCount()得到总结果数
ps.getStartIndex()当前分页索引
ps.getNextIndex()下一页索引
ps.getPreviousIndex()上一页索引
分享到:
评论

相关推荐

    Hibernate 使用DetachedCriteria操作

    - 在服务层进行分页查询时,可以先创建DetachedCriteria,然后在视图层根据请求参数调整限制条件,避免重复计算。 **4. DetachedCriteria 的基本用法** 创建DetachedCriteria通常从`DetachedCriteria.forClass()`...

    Hibernate+sqlserver2000分页

    要将两者结合起来,我们可以创建一个自定义的SQL查询,并在Hibernate的`DetachedCriteria`中使用。这通常涉及到在HQL中嵌入SQL片段,或者使用`createSQLQuery`方法直接执行SQL查询。同时,别忘了映射查询结果到对应...

    springMVC+hibernate的条件查询加分页的demo

    总的来说,"springMVC+hibernate的条件查询加分页的demo"涵盖了Web应用中常见的查询和分页需求,通过SpringMVC接收和处理用户请求,利用Hibernate的Criteria查询动态构造SQL,并通过设置分页参数实现数据的分批次...

    struts2+spring+hibernate分页查询

    综上所述,Struts2、Spring和Hibernate的整合使得开发者能够便捷地实现分页查询,从而优化Web应用的性能和用户体验。在实际项目中,需要根据具体需求和业务场景,选择合适的分页策略和实现方式,同时注意性能优化和...

    hibernate里面的 两种查询

    在Java的持久化框架Hibernate中,查询是连接应用程序与数据库的关键环节。Hibernate提供了两种主要的查询方式:离线查询(Criteria API)和HQL(Hibernate Query Language)语句查询。这两种查询方法各有特点,适用...

    Hibernate3中文文档

    8. ** Criteria API的DetachedCriteria**:DetachedCriteria允许在不打开Session的情况下构建查询,之后在需要时再与Session结合执行,适合于分页查询和延迟加载。 9. **缓存机制**:Hibernate提供了第一级缓存...

    Hibernate 在查询操作中要使用分页+命名参数+排序技术

    在IT行业中,数据库查询是日常开发中的重要环节,特别是在大型应用中,为了提高用户体验和系统性能,分页、命名参数和排序技术的应用至关重要。本文将深入探讨如何在使用Hibernate框架时,有效地结合这些技术进行...

    Hibernate的MySql查询.rar

    本文将深入探讨在使用Hibernate进行MySQL查询时的一些关键知识点,以帮助开发者更好地理解和应用这些技术。 首先,我们需要理解Hibernate的核心概念。Hibernate通过提供一个中间层,将Java对象与数据库表进行映射,...

    hibernate查询详解

    本文将详细介绍Hibernate的五种查询方式,包括HQL查询、Criteria方法、动态查询DetachedCriteria、例子查询、SQL查询以及命名查询,以满足不同场景下的需求。 1. HQL查询: Hibernate Query Language(HQL)是一种...

    Hibernate查询方式代码示例

    本教程将深入探讨Hibernate 3.x版本中的查询方式,包括基本查询、HQL(Hibernate Query Language)以及Criteria API,帮助开发者更高效地处理数据库交互。 1. **基本查询(Criteria API)** Hibernate Criteria ...

    sh分页,增删改查

    Criteria查询提供了动态构建查询的方式,可以通过DetachedCriteria实现分页;HQL是面向对象的查询语言,可以方便地进行分页;对于更复杂的SQL操作,可以直接使用SQL查询,并配合 ScrollableResults 接口实现分页。在...

    Hibernate 查询经典练习题

    在本文中,我们将探讨基于Hibernate的查询实践,包括HQL(Hibernate Query Language)和Criteria API的使用。我们将通过两个经典的练习题来深入理解这两个查询方式,并讨论它们在处理不同查询需求时的特点。 ### ...

    \Hibernate_query条件查询

    Hibernate提供了方便的分页查询功能,无论是HQL还是Criteria API都能实现。例如: ```java // HQL query.setFirstResult(0).setMaxResults(10); // 第一页,每页10条 // Criteria criteria.setFirstResult(0...

    Hibernate中查询的法方

    为了解决这个问题,可以在`DetachedCriteria`中设置相应的查询条件,以实现带条件的分页查询。 通过理解和熟练运用这些基本查询方法,你可以有效地利用Hibernate进行数据操作,从而提高开发效率。在实际项目中,还...

    传智播客_hibernate

    3. **集合分页**: 使用Query的setFirstResult()和setMaxResults()方法实现分页查询,避免一次性加载大量数据。 通过以上讲解,我们可以看到,传智播客的Hibernate教程覆盖了从基础到进阶的各个方面,为初学者提供了...

    Hibernate-基础联表模板

    通过DetachedCriteria、Criteria、Projection等接口,可以方便地实现联表查询,同时支持各种查询条件、排序和分页。 6. **多对一(One-to-Many)和一对多(Many-to-One)关联** 这是两种常见的关联关系。在...

    Hibernate

    6. **查询语言(HQL)**:Hibernate提供的面向对象的查询语言,类似于SQL,但更贴近Java对象,包括简单的查询、复杂查询、条件查询和分页查询。 7. **Criteria API**:另一种进行数据库查询的方式,提供动态构建...

    hibernate-release-5.2.3.Final

    Criteria API提供了一种更灵活的查询方式,通过DetachedCriteria实现离线查询,通过Criteria构建动态查询,结合Projection和Criterion进行结果集处理和条件限制。 8. Hibernate缓存: Hibernate支持二级缓存,...

    Hibernate_3 api

    - 使用Hibernate 3 API,可以方便地实现创建(Create)、读取(Read)、更新(Update)和删除(Delete)数据库记录。例如,`save()`方法用于保存新对象,`update()`用于更新现有对象,`delete()`用于删除对象,`get...

    hibernate in action 中文版书籍

    5. ** Criteria和DetachedCriteria**:详细阐述Criteria查询的使用,包括条件查询、排序、分页,以及DetachedCriteria的概念,用于创建可复用的查询模板。 6. **事务和缓存**:讨论Hibernate的事务管理,包括编程式...

Global site tag (gtag.js) - Google Analytics