Spring+Hibernate 复杂查询分页

原创 2006年06月20日 19:19:00

网上多很多有分页例子,要么不全,要么不能满足复杂查询的要求,下面是本人写的一个初版,给大家参考。

/**分页包装类

很简单 :)

*/

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());


 }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Struts2 Hibernate Spring分页及分页查询

Struts2 Hibernate Spring分页及分页查询     最近学习写了一个分页以及查询的功能。主要就是用了Hibernate的一些功能。直接说吧。。     首页写一个Pag...

spring+hibernate+mysql 分页

最近在做毕业设计,想着每天记录下做了什么吧,这样也方便看看进度。接下来先总结下前几天做的东西,有些是以前就记录好的,这里copy下。 这个是15号做的笔记,我不大习惯做笔记,但是发现这个习惯真的得好...

struts2+hibernate+spring 分页

1、DAO层接口的设计,在MemberDao接口中定义了如下两个方法: public interface MemberDao{          //省略了其他的代码   ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)