关闭

Spring+Hibernate 复杂查询分页

473人阅读 评论(0) 收藏 举报

/**分页包装类

很简单 :)

*/

package com.xing.cms.model.util;

public class Pager {
 private int totalPages = 0;
 private int totalObjects = 0;
 private int pageNumber = 1;
 private int pageSize = 3;
 private boolean pageAble = true;
 
 private int firstResult;
 

 public void calc(){
  totalPages =  totalObjects % pageSize == 0 ? totalObjects
    / pageSize : totalObjects / pageSize + 1;
 
  firstResult = (pageNumber - 1) * pageSize;
 }
 
 public boolean isPageAble() {
  return pageAble;
 }

 public void setPageAble(boolean pageAble) {
  this.pageAble = pageAble;
 }

 public int getTotalObjects() {
  return totalObjects;
 }

 public void setTotalObjects(int param) {
  this.totalObjects = param;
 }

 public int getTotalPages() {
  return totalPages;
 }

 public void setTotalPages(int param) {
  this.totalPages = param;
 }

 public int getPageNumber() {
  return pageNumber;
 }

 public void setPageNumber(int pageNumber) {
  this.pageNumber = pageNumber;
 }

 public int getPageSize() {
  return pageSize;
 }

 public void setPageSize(int pageSize) {
  this.pageSize = pageSize;
 }
 
 public String toString(){
  return("/ntotalPages:" + totalPages +
  "/ntotalObjects:" + totalObjects +
  "/npageNumber:" + pageNumber +
  "/npageSize:" + pageSize +
  "/npageAble:" + pageAble +
  "/nfirstResult:" + firstResult);
 }

 public int getFirstResult() {
  return firstResult;
 }

 public void setFirstResult(int firstResult) {
  this.firstResult = firstResult;
 }
}

/*UserDao 接口*/

package com.xing.cms.model.dao;

import java.util.List;

import com.xing.cms.model.businessobject.User;
import com.xing.cms.model.util.Pager;

public interface UserDao {
 public abstract boolean save(User model);
 public abstract boolean update(User model);
 public abstract User get(int id);
 public abstract boolean delete(int id);
 public abstract void truncate();
 public abstract boolean delete(int[] id);
 public abstract List<User> find(String[][] searchPara,Pager pager);
 public abstract List<User> find(String[][] searchPara);
}

/*UserDao实现*/

package com.xing.cms.model.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
//import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.xing.cms.model.businessobject.User;
import com.xing.cms.model.dao.UserDao;
import com.xing.cms.model.util.GeneralTool;
import com.xing.cms.model.util.Pager;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

 private JdbcTemplate jdbcTemplate;// Spring Injection

 public UserDaoImpl() {
  super();
 }

 public JdbcTemplate getJdbcTemplate() {
  return jdbcTemplate;
 }

 public void setJdbcTemplate(JdbcTemplate param) {
  this.jdbcTemplate = param;
 }

 @SuppressWarnings("unchecked")
 public List<User> find(final String[][] searchPara, final Pager pager) {

  return (List<User>) this.getHibernateTemplate().execute(
    new HibernateCallback() {
     public Object doInHibernate(Session session)
       throws SQLException, HibernateException {
      Criteria ca_count = null;
    
      if(pager.isPageAble())
       ca_count = session.createCriteria(User.class);//不能避免,需要查询两次数据库,这个获取总数
    
      Criteria ca = session.createCriteria(User.class);

      if(searchPara != null){
       ca.setProjection(null);
      for (int i = 0; i < searchPara.length; i++) {

       if (searchPara[i][1].equalsIgnoreCase("=")) {
        if(pager.isPageAble())
         ca_count.add(Restrictions.eq(searchPara[i][0], searchPara[i][2]));
        ca.add(Restrictions.eq(searchPara[i][0], searchPara[i][2]));
       } else if (searchPara[i][1].equalsIgnoreCase("like")) {      
        if(pager.isPageAble())
         ca_count.add(Restrictions.like(searchPara[i][0], searchPara[i][2],MatchMode.ANYWHERE));
        ca.add(Restrictions.like(searchPara[i][0], searchPara[i][2],MatchMode.ANYWHERE));
      
       }

      }
      }
 
      List ret_list;

      if (pager.isPageAble()) {

       pager.setTotalObjects(((Integer) (ca_count
         .setProjection(Projections.rowCount())
         .uniqueResult())).intValue()); //获取Count

 
       pager.calc();
     
       ca.addOrder(Order.desc("UID"));
       ca.setFirstResult(pager.getFirstResult());
       ca.setMaxResults(pager.getPageSize());
       ret_list = ca.list();
 
      } else {
       ca.addOrder(Order.desc("UID"));
       ret_list = ca.list();
     
      }

      return ret_list;
     }
    });
 }

// ......其它方法略去

/*测试类*/

package test;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
import com.xing.cms.model.businessobject.User;
import com.xing.cms.model.dao.DocumentDao;
import com.xing.cms.model.dao.UserDao;
import com.xing.cms.model.util.HtmlGenerator;
import com.xing.cms.model.util.Pager;
import com.xing.cms.model.util.UtilXml;
import com.xing.cms.action.UserAction;

public class TestSpring extends AbstractTransactionalDataSourceSpringContextTests
{
 private Log logger = LogFactory.getLog(TestSpring.class);

 public String[] getConfigLocations() {
  String[] config = new String[]{"applicationContext.xml"};
  return config;
 }


 public void testUserAction() throws Exception{
 
  UserDao dao = (UserDao)applicationContext.getBean("userDao");
  assertTrue(dao!=null);
  User user = (User)applicationContext.getBean("user");
  assertTrue(user!=null);
  Pager pager = (Pager)applicationContext.getBean("pager");
  assertTrue(pager!=null);
  UserAction action = (UserAction)applicationContext.getBean("userAction");
  assertTrue(action!=null);
 
  //clear all first
  dao.truncate();
 
  //super.setComplete();
 
  //add
  for(int i=0;i<20;i++)
  {
   User u = new User();
   u.setGID(1);
   u.setUsername("xzw_"+i);
   u.setPassword("abcd");
   dao.save(u);
  }
 
 
 
  //no pager
 
  /*
  assertEquals(0,dao.find(
    new String[][]{
      new String[]{"username","=","xzw"}
    }
  ).size());
  assertEquals(20,dao.find(null).size());
  */
 
  //with pager
  //action.getPager().setPageSize(9);
  //10 11 12 ... 19 + 1 = 11
 
  /*分页,取第一页,前4 条,应该返回4*/
  action.getPager().setPageSize(4);
  assertEquals(4,dao.find(new String[][]{
    new String[]{"username","like","xzw_1"}
  },action.getPager()).size());

  /*不分页,则取全部的,应该返回20*/
  action.getPager().setPageAble(false);
  action.getPager().setPageSize(4);
  assertEquals(11,dao.find(new String[][]{
    new String[]{"username","like","xzw_1"}
  },action.getPager()).size());

 }
}

 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:103175次
    • 积分:1819
    • 等级:
    • 排名:千里之外
    • 原创:84篇
    • 转载:4篇
    • 译文:0篇
    • 评论:13条