1. 程式人生 > >Hibernate 分頁的兩種方式

Hibernate 分頁的兩種方式

第一種:hql分頁(不推薦)需要手動關閉session連線

//PageBean.java
@SuppressWarnings("hiding")
public class PageBean<T> {
    private int currPage;//當前頁數
    private int pageSize;//每頁顯示的記錄數
    private int total; //總計錄數
    private int totalPage;//總頁數
    private List<T> rows;//每頁顯示的資料

    public int getCurrPage() {
        return
currPage; } public void setCurrPage(int currPage) { this.currPage = currPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotal() { return total; } public
void setTotal(int total) { this.total = total; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public List<T> getRows() { return rows; } public void setRows
(List<T> rows) { this.rows = rows; } }
    //DaoImpl
    //分頁展示User
    @SuppressWarnings("unchecked")
    @Override
    public List<User> getUserByPage(User user, int begin, int pageSize) {
        String hql = "from User where isdeleted=0 ";
        //拼裝查詢條件
        hql = getHqlWhere(user, hql);
        hql+=" order by modifytime desc";

        Session session = this.getHibernateTemplate().getSessionFactory().openSession();
        Query query = session.createQuery(hql);
        query.setFirstResult(begin);
        query.setMaxResults(pageSize);
        List<User> userList = query.list();
        releaseSession(session);

        return userList;
    }

    public int getUserCount(User user){
        String hql = "select count(*) from User where isdeleted=0 ";
        //拼裝查詢條件
        hql = getHqlWhere(user, hql);
        List<Long> list = this.getHibernateTemplate().find(hql);
        if(list.size()>0){
            return list.get(0).intValue();
        }
        return 0;
    }

    //hql查詢條件拼裝方法
    private String getHqlWhere(User user,String hql){
        if(user!=null){
            if(user.getUsername()!=null&&!user.getUsername().isEmpty()){
                hql+=" and username like '%"+user.getUsername()+"%'";
            }
            if(user.getZsxm()!=null&&!user.getZsxm().isEmpty()){
                hql+=" and zsxm like '%"+user.getZsxm()+"%'";
            }
            if(user.getFjid()!=null&&!user.getFjid().isEmpty()&&!user.getFjid().equals("0")){
                hql+=" and fjid='"+user.getFjid()+"'";
            }
        }
        return hql;
    }
    //serverImpl
    @Override
    /**
     *  user分頁查詢方法
     * @param user   儲存查詢條件
     * @param currPage 當前頁數
     * @param pageSize 每頁顯示多少行
     * @return
     */
    public PageBean<User> getUserByPage(User user, Integer currPage, Integer pageSize) {

        PageBean<User> pageBean = new PageBean<User>();
        pageBean.setCurrPage(currPage);//當前頁數
        pageBean.setPageSize(pageSize);//每頁顯示多少行
        //總記錄數
        int totalCount = userDao.getUserCount(user);
        pageBean.setTotal(totalCount);
        //總頁數
        double tc = totalCount;
        Double num = Math.ceil(tc/pageSize);//存在小數位直接進一
        pageBean.setTotalPage(num.intValue());
        //封裝每頁顯示的資料
        int begin = (currPage-1)*pageSize;
        List<User> userList = userDao.getUserByPage(user, begin, pageSize);
        pageBean.setRows(userList);

        return pageBean;
    }

//Action();
public void list() {
        PageBean<User> pageBean = userService.getUserByPage(user, page, rows);
        Gson gson = new Gson();
        try {
            System.out.println(gson.toJson(pageBean));
//json格式輸出分頁查詢資料
            Utils.sendMsg(gson.toJson(pageBean));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

第二種:DetachedCriteria (推薦使用)

    //分頁展示User
    @SuppressWarnings("unchecked")
    @Override
    public List<User> getUserByPage(User user, int begin, int pageSize) {
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
        if(user!=null){
            if(user.getUsername()!=null&&!user.getUsername().isEmpty()){
                DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
        if(user!=null){
            if(user.getUsername()!=null&&!user.getUsername().isEmpty()){
                //criteria.add(Restrictions.like("username", "%"+user.getUsername()+"%"));
                 criteria.add(Restrictions.like("username", user.getUsername(),MatchMode.ANYWHERE));
            }
            if(user.getZsxm()!=null&&!user.getZsxm().isEmpty()){
                criteria.add(Restrictions.like("zsxm", "%"+user.getZsxm()+"%"));
            }
            if(user.getFjid()!=null&&!user.getFjid().isEmpty()&&!user.getFjid().equals("0")){
                criteria.add(Restrictions.eq("fjid", user.getFjid()));
            }
        }
        List<User> userList = this.getHibernateTemplate().findByCriteria(criteria, begin, pageSize);

        return userList;
    }

備註:若DetachedCriteria where 後面多個條件是or

/*
                 *  Hibernate 查詢MatchMode的四種模式
                    MatchMode.START:字串在最前面的位置.相當於"like 'key%'"
                    MatchMode.END:字串在最後面的位置.相當於"like '%key'"
                    MatchMode.ANYWHERE:字串在中間匹配.相當於"like '%key%'"
                    MatchMode.EXACT:字串精確匹配.相當於"like 'key'"
                 */
                //sql where or
                Disjunction disjunction = Restrictions.disjunction();  
                disjunction.add(Restrictions.like("tel",contacts.getSearchTel(),MatchMode.ANYWHERE));
                disjunction.add(Restrictions.like("mphone",contacts.getSearchTel(),MatchMode.ANYWHERE));
                disjunction.add(Restrictions.like("ephone",contacts.getSearchTel(),MatchMode.ANYWHERE));
                criteria.add(disjunction);