之前写了个分页查询,感觉还是比较通用的,虽然还有一点问题 也希望大家指点一下。我用的Hibernate.
pager的帮助类:
1 import java.util.List;
2
3 /**
4 * @author AsceticJ
5 * @date 2017年5月28日 下午9:09:01
6 * @version 1.0
7 * @param <T>
8
9 * @TODO 分页帮助类:在Action里传参设置pager的参数,在需要分页的页面使用include指令导入webroot目录下pager.jsp
10 */
11 public class Pager<T>
12 {
13 //action传值得到
14 private Integer currPage=1;//设置当前页,默认显示第一页
15 private Integer pageSize=10;//每页显示记录数,默认显示10条
16 private Integer indexSize=5;//设置需要显示页码的总数,默认显示5页
17 private String actionName;//设置跳转到第N页的action名称
18 //查询得到
19 private Integer totalCount;//总记录数
20 private List<T> countList;//用于存放每页记录的集合
21 //计算得到
22 private Integer totalPage;//总页数
23 //用于设置页码显示
24 private Integer beginIndex;//显示的开始页码
25 private Integer endIndex;//显示的结束页码
26
27 public Pager(){}
28
29 public Pager(Integer currPage, Integer pageSize ,Integer totalCount ,List<T> countList)
30 {
31 this.currPage = currPage;
32 this.pageSize = pageSize;
33 this.totalCount = totalCount;
34 this.countList = countList;
35 //设置总页数
36 this.totalPage = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
37 //设置页码
38 //中间情况
39 this.beginIndex = currPage - (indexSize-1)/2;
40 this.endIndex = currPage + indexSize/2;
41 //首端
42 if (beginIndex < 1)
43 {
44 beginIndex = 1;
45 endIndex = totalPage<indexSize?totalPage:indexSize;
46 }
47 //末端
48 if (endIndex > totalPage)
49 {
50 endIndex = totalPage;
51 beginIndex = totalPage<indexSize?1:totalPage-indexSize+1;
52 }
53 }
54 //设置带有显示页码数量的pager
55 public Pager(Integer currPage,Integer pageSize ,Integer indexSize ,Integer totalCount ,List<T> countList)
56 {
57 this.currPage = currPage;
58 this.pageSize = pageSize;
59 this.totalCount = totalCount;
60 this.countList = countList;
61 //设置总页数
62 this.totalPage = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
63 //设置页码
64 int halfSize= (indexSize-1)/2;
65 //中间情况
66 this.beginIndex = currPage - halfSize;
67 this.endIndex = currPage + halfSize + 1;
68 //首端
69 if (beginIndex < 1)
70 {
71 beginIndex = 1;
72 endIndex = totalPage<indexSize?totalPage:indexSize;
73 }
74 //末端
75 if (endIndex > totalPage)
76 {
77 endIndex = totalPage;
78 beginIndex = totalPage<indexSize?1:totalPage-indexSize+1;
79 }
80 }
81
82 //============get/set====================
83 public Integer getCurrPage()
84 {
85 return currPage;
86 }
87 public void setCurrPage(Integer currPage)
88 {
89 this.currPage = currPage;
90 }
91 public Integer getTotalCount()
92 {
93 return totalCount;
94 }
95 public void setTotalCount(Integer totalCount)
96 {
97 this.totalCount = totalCount;
98 }
99 public Integer getPageSize()
100 {
101 return pageSize;
102 }
103 public void setPageSize(Integer pageSize)
104 {
105 this.pageSize = pageSize;
106 }
107 public Integer getTotalPage()
108 {
109 return totalPage;
110 }
111 public void setTotalPage(Integer totalPage)
112 {
113 this.totalPage = totalPage;
114 }
115 public List<T> getCountList()
116 {
117 return countList;
118 }
119 public void setCountList(List<T> countList)
120 {
121 this.countList = countList;
122 }
123 public Integer getIndexSize()
124 {
125 return indexSize;
126 }
127 public void setIndexSize(Integer indexSize)
128 {
129 this.indexSize = indexSize;
130 }
131
132 public Integer getBeginIndex()
133 {
134 return beginIndex;
135 }
136
137 public void setBeginIndex(Integer beginIndex)
138 {
139 this.beginIndex = beginIndex;
140 }
141
142 public Integer getEndIndex()
143 {
144 return endIndex;
145 }
146
147 public void setEndIndex(Integer endIndex)
148 {
149 this.endIndex = endIndex;
150 }
151
152 public String getActionName()
153 {
154 return actionName;
155 }
156
157 public void setActionName(String actionName)
158 {
159 this.actionName = actionName;
160 }
161
162 }
View Code
我是在BaseDao里面对分页进行封装的(里面写了几种查询的方法,我用的是findByCriteria)。
1 import java.lang.reflect.Field;
2 import java.lang.reflect.InvocationTargetException;
3 import java.lang.reflect.Method;
4 import java.lang.reflect.ParameterizedType;
5 import java.util.ArrayList;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Map;
9
10 import javax.annotation.Resource;
11
12 import org.hibernate.Criteria;
13 import org.hibernate.Query;
14 import org.hibernate.Session;
15 import org.hibernate.SessionFactory;
16 import org.hibernate.criterion.DetachedCriteria;
17 import org.hibernate.criterion.Projections;
18 import org.hibernate.criterion.Restrictions;
19 import org.springframework.orm.hibernate3.HibernateTemplate;
20 import org.springframework.stereotype.Repository;
21 import org.springframework.transaction.annotation.Transactional;
22
23 import com.eduask.group8.dao.IBaseDao;
24 import com.eduask.group8.pojo.Pager;
25
26 /**
27 * @author AsceticJ
28 * @date 2017年5月23日 上午9:32:28
29 * @version 1.0
30
31 * @TODO Dao层基础类
32 */
33
34 @SuppressWarnings("all")
35 @Repository
36 @Transactional
37 public abstract class BaseDaoImpl<T> implements IBaseDao<T>{
38 @Resource
39 private SessionFactory sessionFactory;
40
41 private Class<T> classObject;
42
43 public BaseDaoImpl(){
44 /* 使用反射技术得到T的真实类型 */
45 // 获取当前new的对象的 泛型的父类 类型(即获得BaseDaoImpl<T>)
46 ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
47 // 获取第一个类型参数的真实类型(即获得<T>中的T)
48 this.classObject = (Class<T>) pt.getActualTypeArguments()[0];
49 }
50
51 protected Session getSession(){
52 return sessionFactory.getCurrentSession();
53 }
54 //获取hibernateTemplate
55 private HibernateTemplate hibernateTemplate;
56 protected HibernateTemplate getHibernateTemplate(){
57 if(hibernateTemplate==null){
58 hibernateTemplate = new HibernateTemplate(sessionFactory);
59 }
60 return hibernateTemplate;
61 }
62
63
64 @Override
65 public void add(T t) {
66 getSession().save(t);
67 }
68
69 @Override
70 public void del(Integer id) {
71 Session session=getSession();
72 T t=(T)session.get(classObject, id);
73 session.delete(t);
74 }
75
76 @Override
77 public void update(T t) {
78 getSession().update(t);
79 }
80
81 @Override
82 public T getById(Integer id) {
83 return (T)getSession().get(classObject, id);
84 }
85
86 @Override
87 public List<T> getAll() {
88 /*
89 * 如果实现了HibernateSupport接口的写法
90 * return getHibernateTemplate.find("from "+classObject.getSimpleName());
91 */
92 String hqlForResult="from "+classObject.getSimpleName();
93 return getSession().createQuery(hqlForResult).list();
94 }
95
96 @Override
97 public Pager<T> getAll(Integer currPage,Integer pageSize) {
98 String hqlForResult="from "+classObject.getSimpleName();
99 return usePage(currPage, pageSize, hqlForResult);
100 }
101
102
103 //-------------------------------------------------------------------------
104 // 使用HibernateTemplate进行查询
105 //-------------------------------------------------------------------------
106 //使用HibernateTemplate的find()方法:多条件模糊查询,未分页
107 public List<T> find(T t,String[] fieldNames) throws Exception
108 {
109 //使用hibernateTemplate的find()方法
110 String hql = "from "+classObject.getSimpleName()+" where 1=1 ";
111 //获取属性名的get方法
112 String[] getMethodNames = new String[fieldNames.length];
113 Method[] getFieldValues = new Method[fieldNames.length];
114 List<Object> paramList = new ArrayList<Object>();
115 for (int i = 0; i < fieldNames.length; i++)
116 {
117 getMethodNames[i] = "get"+fieldNames[i].substring(0,1).toUpperCase()+fieldNames[i].substring(1);
118 getFieldValues[i] = classObject.getMethod(getMethodNames[i], null);
119 //拼hql语句
120 if (null!=getFieldValues[i]&&!"".equals(getFieldValues[i]))
121 {
122 hql+="and "+fieldNames[i]+" like ?";
123 paramList.add("%"+getFieldValues[i]+"%");
124 }
125 }
126 List<T> countList = getHibernateTemplate().find(hql, paramList.toArray());
127 return countList;
128 }
129
130 //使用HibernateTemplate的findByCriteria()方法:多条件模糊查询带分页
131 public Pager<T> findByHibernateCriteria(T t,String[] fieldNames,Integer currPage,Integer pageSize){
132 //获得离线对象
133 DetachedCriteria criteria = DetachedCriteria.forClass(classObject);
134 //用于接收getFiledName的方法名数组
135 String[] getMethodNames = new String[fieldNames.length];
136 //用于接收getFiledName的方法数组
137 Method[] getFieldValues = new Method[fieldNames.length];
138 for (int i = 0; i < fieldNames.length; i++)
139 {
140 getMethodNames[i] = "get"+fieldNames[i].substring(0,1).toUpperCase()+fieldNames[i].substring(1);
141 try
142 {
143 //获得所有getFiledName的方法
144 getFieldValues[i] = classObject.getMethod(getMethodNames[i], null);
145 //给离线对象添加查询条件
146 if (null!=getFieldValues[i]&&!"".equals(getFieldValues[i]))
147 {
148 criteria.add(Restrictions.like(fieldNames[i], "%"+getFieldValues[i].invoke(t, null)+"%"));
149 }
150 } catch (Exception e)
151 {
152 e.printStackTrace();//使用反射获取当前实体对象的属性的值失败
153 return null;
154 }
155 }
156 //设置分页
157 //判断当前页是否为空
158 currPage = null==currPage?1:currPage;
159 //获取总记录数
160 int totalCount = 0;
161 Criteria c = getSession().createCriteria(classObject);
162 c.setProjection(Projections.rowCount());
163 totalCount = Integer.parseInt(c.uniqueResult().toString());
164 //获取单页的结果集
165 List<T> countList = getHibernateTemplate().findByCriteria(criteria,(currPage-1)*pageSize,pageSize);
166 return new Pager<T>(currPage, pageSize, totalCount, countList);
167 }
168
169 //使用将属性和值均传递过来(或者json)
170 public Pager<T> findByHibernateCriteria(Map<String, Object> fieldMap,Integer currPage,Integer pageSize){
171 //获得离线对象
172 DetachedCriteria criteria = DetachedCriteria.forClass(classObject);
173 //设置查询条件
174 for(String s : fieldMap.keySet()){
175 criteria.add(Restrictions.like(s, "%"+fieldMap.get(s)+"%"));
176 }
177 //设置分页
178 //判断当前页是否为空
179 currPage = null==currPage?1:currPage;
180 //获取总记录数
181 int totalCount = 0;
182 Criteria c = getSession().createCriteria(classObject);
183 c.setProjection(Projections.rowCount());
184 totalCount = Integer.parseInt(c.uniqueResult().toString());
185 //获取单页的结果集
186 List<T> countList = getHibernateTemplate().findByCriteria(criteria,(currPage-1)*pageSize,pageSize);
187 return new Pager<T>(currPage, pageSize, totalCount, countList);
188 }
189
190 //使用HibernateTemplate的findByCriteria()方法:多条件模糊查询带分页
191 public Pager<T> findByHibernateCriteria(T t,Integer currPage,Integer pageSize){
192 //获得离线对象
193 DetachedCriteria criteria = DetachedCriteria.forClass(classObject);
194 //获取实体对象的所有字段
195 Field[] fields = classObject.getDeclaredFields();
196 //用于接收getFiledName的方法名数组
197 String[] getMethodNames = new String[fields.length];
198 //用于接收getFiledName的方法数组
199 Method[] getFieldValues = new Method[fields.length];
200 for (int i = 0; i < fields.length; i++)
201 {
202 getMethodNames[i] = "get"+fields[i].getName().substring(0,1).toUpperCase()+fields[i].getName().substring(1);
203 try
204 {
205 //获得所有getFiledName的方法
206 getFieldValues[i] = classObject.getMethod(getMethodNames[i], null);
207 //给离线对象添加查询条件
208 if (null!=getFieldValues[i]&&!"".equals(getFieldValues[i]))
209 {
210 criteria.add(Restrictions.like(fields[i].getName(), "%"+getFieldValues[i].invoke(t, null)+"%"));
211 }
212 } catch (Exception e)
213 {
214 e.printStackTrace();//使用反射获取当前实体对象的属性的值失败
215 return null;
216 }
217 }
218 //设置分页
219 //判断当前页是否为空
220 currPage = null==currPage?1:currPage;
221 //获取总记录数
222 int totalCount = 0;
223 Criteria c = getSession().createCriteria(classObject);
224 c.setProjection(Projections.rowCount());
225 totalCount = Integer.parseInt(c.uniqueResult().toString());
226 //获取单页的结果集
227 List<T> countList = getHibernateTemplate().findByCriteria(criteria,(currPage-1)*pageSize,pageSize);
228 return new Pager<T>(currPage, pageSize, totalCount, countList);
229 }
230
231
232
233 //-------------------------------------------------------------------------
234 // 使用Criteria进行查询
235 //-------------------------------------------------------------------------
236 //使用Criteria分页查询,未使用HibernateTemplate
237 public Pager<T> findByCriteria(Integer currPage,Integer pageSize)
238 {
239 Criteria criteria = getSession().createCriteria(classObject);
240 //判断当前页是否为空
241 currPage = null==currPage?1:currPage;
242 //获取总记录数
243 int totalCount = 0;
244 criteria.setProjection(Projections.rowCount());
245 totalCount = Integer.parseInt(criteria.uniqueResult().toString());
246
247 //获得当前页的List集合
248 Criteria criteria2 = getSession().createCriteria(classObject);
249 criteria2.setFirstResult((currPage-1)*pageSize).setMaxResults(pageSize);
250 List<T> countList = criteria2.list();
251 return new Pager<T>(currPage,pageSize,totalCount,countList);
252 }
253
254 //使用criteria进行条件查询分页
255 public Pager<T> findByCriteria(T t,Integer currPage,Integer pageSize){
256 //当传过来的实体对象不存在,说明没有查询条件的限制
257 if (null==t)
258 {
259 return findByCriteria(currPage,pageSize);
260 }
261 //获得criteria对象
262 Criteria criteria = getSession().createCriteria(classObject);
263 //设置查询条件
264 setConditions(t, criteria);
265 //设置分页
266 //判断当前页是否为空
267 currPage = null==currPage?1:currPage;
268 //获取总记录数
269 Integer totalCount = 0;
270 criteria.setProjection(Projections.rowCount());
271 totalCount = Integer.parseInt(criteria.uniqueResult().toString());
272 //获取单页的结果集
273 Criteria c = getSession().createCriteria(classObject);
274 setConditions(t, c);
275 List<T> countList = c.setFirstResult((currPage-1)*pageSize).setMaxResults(pageSize).list();
276 return new Pager<T>(currPage, pageSize, totalCount, countList);
277 }
278
279 //设置查询条件
280 public void setConditions(T t, Criteria criteria)
281 {
282 //获取实体对象的所有字段
283 Field[] fields = classObject.getDeclaredFields();
284 //用于接收getFiledName的方法名数组
285 String[] getMethodNames = new String[fields.length];
286 //用于接收getFiledName的方法数组
287 Method[] getFieldValues = new Method[fields.length];
288 //用于临时存放getgetFiledName的方法的执行结果
289 Object fieldValue=null;
290 for (int i = 0; i < fields.length; i++)
291 {
292 getMethodNames[i] = "get"+fields[i].getName().substring(0,1).toUpperCase()+fields[i].getName().substring(1);
293 try
294 {
295 //获得所有getFiledName的方法
296 getFieldValues[i] = classObject.getMethod(getMethodNames[i], null);
297 //获取参数的值
298 fieldValue = getFieldValues[i].invoke(t, null);
299 //给离线对象添加查询条件
300 if (null!=fieldValue&&!"".equals(fieldValue)&&fieldValue!=Integer.valueOf(0))
301 {
302 if (fieldValue.getClass().getSimpleName().equals("Integer"))
303 {
304 criteria.add(Restrictions.eq(fields[i].getName(), fieldValue));
305 }else{
306 criteria.add(Restrictions.like(fields[i].getName(), "%"+fieldValue+"%"));
307 }
308 }
309 } catch (Exception e)
310 {
311 e.printStackTrace();//使用反射获取当前实体对象的属性的值失败
312 }
313 }
314 }
315
316
317
318 //-------------------------------------------------------------------------
319 // 使用hql语句进行操作
320 //-------------------------------------------------------------------------
321 //hql已经拼接完成,单纯在原来基础上进行分页,不需要设置参数
322 public Pager<T> usePage(Integer currPage,Integer pageSize,String hqlForResult){
323 //获取总记录数
324 int totalCount = 0;
325 Number c = (Number) getSession().createQuery("select count(*) "+hqlForResult).uniqueResult();
326 totalCount = c.intValue();
327 //判断当前页是否为空
328 currPage = null==currPage?1:currPage;
329 //获得当前页的List集合
330 Query query=getSession().createQuery(hqlForResult);
331 query.setFirstResult((currPage-1)*pageSize).setMaxResults(pageSize);
332 List<T> countList = query.list();
333 return new Pager<T>(currPage,pageSize,totalCount,countList);
334 }
335
336 //hql语句多条件分页查询
337 //固定查询条件,而且均是必填内容
338 //这里的hql语句是带问号需要设置参数的,当别人未填写时有问题
339 public Pager<T> findByPage(String hql,String [] parameters,Integer pageSize,Integer currPage){
340 //获取总记录数
341 int totalCount = 0;
342 Query queryCounts = getSession().createQuery("select count(*) "+hql);
343 //先判断是否有参数要绑定
344 if(parameters!=null&& parameters.length>0){
345 for(int i=0;i<parameters.length;i++){
346 queryCounts.setString(i, parameters[i]);
347 }
348 }
349 totalCount = ((Number)queryCounts.uniqueResult()).intValue();
350 //查询数据设置分页
351 Query query=getSession().createQuery(hql);
352 //先判断是否有参数要绑定
353 if(parameters!=null&& parameters.length>0){
354 for(int i=0;i<parameters.length;i++){
355 query.setString(i, parameters[i]);
356 }
357 }
358 //设置分页
359 query.setFirstResult((currPage-1)*pageSize).setMaxResults(pageSize);
360 List<T> countList=query.list();
361 return new Pager<T>(currPage,pageSize,totalCount,countList);
362 }
363
364 //hql语句进行update或delete操作
365 public void executeUpdate(String hql,String [] parameters){
366 Query query = getSession().createQuery(hql);
367 //先判断是否有参数要绑定
368 if(parameters!=null&& parameters.length>0){
369 for(int i=0;i<parameters.length;i++){
370 query.setString(i, parameters[i]);
371 }
372 }
373 query.executeUpdate();
374 }
375
376
377 }
View Code
JSP页面静态导入的pager.jsp
<%@ page pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<!-- 写一个点击事件,将form表单(ID为search_form)内的所有含有name属性且value不为空的元素获取到,然后获取分页a标签的href值,往url上将name和value添加上去 -->
<script type="text/javascript">
function changeAnchorUrl(obj){
var pageUrl = $(obj).attr("data");
var searchForm = $("#search_form");
var formUrl = searchForm.attr("action");
console.log(formUrl+"&"+pageUrl);
if(formUrl.indexOf("?")==-1){
searchForm.attr("action",formUrl+"?"+pageUrl);
}else{
searchForm.attr("action",formUrl+"&"+pageUrl);
}
searchForm.submit();
}</script>
<body>
<div id="pages">
<c:if test="${pager.currPage!=1}">
<a data="pager.currPage=${pager.currPage-1}" onclick="changeAnchorUrl(this)">上一页</a>
</c:if>
<c:if test="${pager.totalPage>1}">
<c:forEach var="index" begin="${pager.beginIndex}" end="${pager.endIndex}">
<a data="pager.currPage=${index}" onclick="changeAnchorUrl(this)" class="${pager.currPage==index?'current_page':''}">${index}</a>
</c:forEach>
</c:if>
<c:if test="${pager.currPage!=pager.totalPage&&0!=pager.totalPage}">
<a data="pager.currPage=${pager.currPage+1}" onclick="changeAnchorUrl(this)" >下一页</a>
</c:if>
</div>
</body>
</html>