有的代碼是拷貝來的。搗鼓了半天才好用。mybatis自帶的分頁是內存的。測試了下10W條的數據。立馬內存溢出,只能自己瞎寫了。
爲了其他人使用的時候方便可能寫的有點麻煩。
代碼下載地址:http://download.csdn.net/detail/fairyhawk/4938207
有錯誤或者不好的地方請指正下,多分享~
一、先貼下開發人員使用時需要寫的4個地方
1.action,比普通方法多傳個分頁的this.getPage()就可以。
/**
* 分頁demo
* @return String
*/
public String testpage() {
try {
this.getPage().setPageSize(50);//設置每頁爲50,默認10
customerLists = customerService.getCustomerName(getQueryCondation(),
this.getPage());
} catch (Exception e) {
logger.error("test page error:",e);
return ERROR;
}
return "testpage";
}
2 jsp.顯示,在頁面下方引用公用的分頁jsp <body>
<s:iterator value="customerLists" var="customer">
<s:property value="#customer.email"/><br/>
</s:iterator>
<jsp:include page="/WEB-INF/jsp/common/page.jsp" />
</body>
3.實現類:傳入參數,sql.條件類和分頁類
(分頁一般會用2個SQL,一個查詢數據list,另一個查詢總行數,這個地方只設置了一個。另一個必須命名爲加PageCount)
public List<Customer> getCustomerName(CustomerQueryCondition queryCondition,PageEntity page){
return this.queryForListPage("CustomerMapper.getCustest", queryCondition,page);
};
4.mybstis sql:如3所注意的命名
getCustest,另一個計算count的sql必須命名爲getCustestPageCount,也可以讓3的實現類傳2個sql.就可以隨便命名了。。。
<!-- 分頁demo Sql-->
<select id="getCustest" parameterType="java.util.HashMap" resultMap="csutomerMap">
select * from cus_customer_tbl where
<![CDATA[ cus_id <#{pageCondition.cusId,jdbcType=INTEGER} ]]>
order by cus_id desc
<include refid="publicMapper.pageEnd"/>
</select>
<select id="getCustestPageCount" parameterType="java.util.HashMap" resultType="java.lang.Integer">
select count(1) from cus_customer_tbl where
<![CDATA[ cus_id <#{pageCondition.cusId,jdbcType=INTEGER} ]]>
</select>
個人使用的時候應該只需要注意這4個地方就可以了。誰有更簡便的求代碼~
二、下面貼一下詳細的代碼。其實重要的地方就3個地方。1. BaseService裏返回分頁的方法queryForListPage,2.CommonAction獲得頁面請求的參數,3,分頁page.jsp
customerAction,繼承CommonAction
package com.ssi.edu.customer.action;
import java.util.List;
import org.apache.log4j.Logger;
import com.ssi.common.action.CommonAction;
import com.ssi.edu.customer.dto.CustomerQueryCondition;
import com.ssi.edu.customer.entity.Customer;
import com.ssi.edu.customer.iservice.ICustomerService;
public class CustomerAction extends CommonAction {
/**
* serialVersionUID
*/
private static final long serialVersionUID = -5437567400651524629L;
private static final Logger logger = Logger.getLogger(CustomerAction.class);
private ICustomerService customerService;
private List<Customer> customerLists;
CustomerQueryCondition queryCondition;
/**
* 分頁demo
* @return String
*/
public String testpage() {
try {
this.getPage().setPageSize(50);//設置每頁爲50,默認10
customerLists = customerService.getCustomerName(getQueryCondation(),
this.getPage());
} catch (Exception e) {
logger.error("test page error:",e);
return ERROR;
}
return "testpage";
}
/**
* ajax demo
* @return
*/
public String tesajax() {
this.getPage().setPageSize(50);
customerLists = customerService.getCustomerName(getQueryCondation(),
this.getPage());
return "json";
}
public ICustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(ICustomerService customerService) {
this.customerService = customerService;
}
public List<Customer> getCustomerLists() {
return customerLists;
}
public void setCustomerLists(List<Customer> customerLists) {
this.customerLists = customerLists;
}
public CustomerQueryCondition getQueryCondation() {
if (queryCondition == null) {
queryCondition = new CustomerQueryCondition();
}
return queryCondition;
}
public void setQueryCondation(CustomerQueryCondition queryCondition) {
this.queryCondition = queryCondition;
}
}
CommonAction:主要定義page變量和
getServletRequestUrlParms 方法~
public class CommonAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = -2257300693413224000L;
ActionContext context = ActionContext.getContext();
/** 分頁頁面地址及參數 */
private String servletRequestParms;
/** log對象 */
private static final Logger logger = Logger.getLogger(CommonAction.class);
/** request對象 */
protected HttpServletRequest servletRequest;
/** response對象 */
private HttpServletResponse servletResponse;
private PageEntity page;
public HttpServletRequest getServletRequest() {
return (HttpServletRequest) (servletRequest != null ? servletRequest : context.get(ServletActionContext.HTTP_REQUEST));
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public HttpServletResponse getServletResponse() {
return (HttpServletResponse) (servletResponse != null ? servletResponse : context.get(ServletActionContext.HTTP_RESPONSE));
}
public void setServletResponse(HttpServletResponse servletResponse) {
this.servletResponse = servletResponse;
}
/**
* 獲取URL及參數
*
* @return
*/
public String getServletRequestUrlParms(){
//獲得的地址參數,如果沒有爲空 ,有時是以&結束的
StringBuffer sbUrlParms = getServletRequest().getRequestURL();
sbUrlParms.append("?");
@SuppressWarnings("rawtypes")
Enumeration parNames = getServletRequest().getParameterNames();
while (parNames.hasMoreElements()) {
String parName = parNames.nextElement().toString();
try {
sbUrlParms.append(parName).append("=").append(
URLEncoder.encode(getServletRequest().getParameter(parName),"UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
logger.error("基類獲取分頁參數錯誤", e);
return "";
}
}
return sbUrlParms.toString();
}
public void setServletRequestParms() {
this.servletRequestParms = getServletRequestUrlParms();
}
public String getServletRequestParms() {
servletRequestParms=getServletRequestUrlParms();
return servletRequestParms;
}
public void setServletRequestParms(String servletRequestParms) {
this.servletRequestParms = servletRequestParms;
}
public void setSession(String name, Object o) {
ActionContext.getContext().getSession().put(name, o);
}
@SuppressWarnings("unchecked")
public <T extends Object> T getSession(String name) {
if (ActionContext.getContext().getSession().get(name) == null) {
return null;
} else {
return (T) ActionContext.getContext().getSession().get(name);
}
}
public PageEntity getPage() {
if (page==null){
page =new PageEntity();
}
return page;
}
public void setPage(PageEntity page) {
this.page = page;
}
}
實現類,繼承BaseService
package com.ssi.edu.customer.serviceImpl;
import java.util.List;
import com.ssi.common.entity.PageEntity;
import com.ssi.common.service.BaseService;
import com.ssi.edu.customer.dto.CustomerQueryCondition;
import com.ssi.edu.customer.entity.Customer;
import com.ssi.edu.customer.iservice.ICustomerService;
public class ICustomerServiceImpl extends BaseService implements ICustomerService {
public List<Customer> getCustomerName(CustomerQueryCondition queryCondition,PageEntity page){
return this.queryForListPage("CustomerMapper.getCustest", queryCondition,page);
};
public List<Customer> getCustomerName(CustomerQueryCondition queryCondition){
return this.getMyBatisDao().selectList("CustomerMapper.getCustomerListJson", queryCondition);
};
}
BaseService:主要定義了dao接口和分頁的方法。分頁的也可以直接寫在mybatisdao的實現裏。我單獨放這邊了。。
package com.ssi.common.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ssi.common.dao.MyBatisDao;
import com.ssi.common.entity.PageEntity;
import com.ssi.common.entity.PageOL;
public abstract class BaseService {
private MyBatisDao myBatisDao;
public MyBatisDao getMyBatisDao() {
return myBatisDao;
}
public void setMyBatisDao(MyBatisDao myBatisDao) {
this.myBatisDao = myBatisDao;
}
/**
* 分頁查詢時使用
*
* @return
*/
public <T> List<T> queryForListPage(String sqlKey, Object params,
PageEntity page) {
/**
* 分頁時需要2個sql。在正常sql後面加pageCount爲計算count的sql
* 如:customre.getcustomreByTime必須命名爲customre.getcustomreByTimePageCount
*/
// 查詢總行數
Map<String, Object> map = new HashMap<String, Object>();
map.put("pageCondition", params);
PageOL pageOL = new PageOL();
pageOL.setOffsetPara((page.getCurrentPage() - 1)
* page.getPageSize());
pageOL.setLimitPara(page.getPageSize());
map.put("page", pageOL);
Integer objectscount = this.getMyBatisDao().selectOne(
sqlKey+ "PageCount",
map);
if (objectscount == null || objectscount == 0) {
page.setTotalResultSize(0);
int totalPageSize = (page.getTotalResultSize() - 1)
/ page.getPageSize() + 1;
page.setTotalPageSize(totalPageSize);
return null;
} else {
page.setTotalResultSize(objectscount);
int totalPageSize = (page.getTotalResultSize() - 1)
/ page.getPageSize() + 1;
page.setTotalPageSize(totalPageSize);
return this.getMyBatisDao().selectList(sqlKey, map);
}
}
}
MyBatisDaoImpl實現類:這個沒什麼東西。跟mybatis的sqlsession的方法一樣。
package com.ssi.common.dao;
import java.util.List;
import org.mybatis.spring.support.SqlSessionDaoSupport;
public class MyBatisDaoImpl extends SqlSessionDaoSupport implements MyBatisDao{
public int insert(String sqlKey, Object object) {
return (Integer) this.getSqlSession().insert(sqlKey, object);
}
public int delete(String sqlKey, Object object) {
return this.getSqlSession().delete(sqlKey, object);
}
public int update(String key, Object object) {
return getSqlSession().update(key, object);
}
@SuppressWarnings("unchecked")
public <T> T selectOne(String sqlKey, Object params) {
return (T) this.getSqlSession().selectOne(sqlKey, params);
}
public <T> List<T> selectList(String sqlKey, Object params) {
return this.getSqlSession().selectList(sqlKey, params);
}
}
分頁的jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ include file="/WEB-INF/inc/header.inc" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<s:if test="page != null" >
<table border="0" width="100%" height="100%" class="lists_td_ablock">
<tr>
<td>
共有 <s:property value="page.totalResultSize"/> 條記錄,當前第 <s:property value="page.currentPage"/>/<s:property value="page.totalPageSize"/> 頁
</td>
<td width="45">
<s:if test="!page.first">
<a href="#" οnclick="goPage(1);">
</s:if>
<img src="<%=contextPath%>/back/images/first.gif" />
<s:if test="!page.first">
</a>
</s:if>
</td>
<td width="45">
<s:if test="!page.first">
<a href="#" οnclick="goPage(<s:property value="page.currentPage-1"/>);">
</s:if>
<img src="<%=contextPath%>/back/images/back.gif" />
<s:if test="!page.first">
</a>
</s:if>
</td>
<td id="goPageByNumber" width="15">
</td>
<td width="45">
<s:if test="!page.last">
<a href="#" οnclick="goPage(<s:property value="page.currentPage+1"/>);">
</s:if>
<img src="<%=contextPath%>/back/images/next.gif" />
<s:if test="!page.last">
</a>
</s:if>
</td>
<td width="45">
<s:if test="!page.last">
<a href="#" οnclick="goPage(<s:property value="page.totalPageSize"/>);">
</s:if>
<img src="<%=contextPath%>/back/images/last.gif" />
<s:if test="!page.last">
</a>
</s:if>
</td>
<td width="50">
<div align="center"><span class="STYLE1">轉到第</span></div>
</td>
<td width="25">
<div align="center"><span class="STYLE1">
<input name="textfield" id="pageNoIpt" type="text" size="4" style="height:16px; margin-top:2px; width:24px; border:1px solid #999999;" />
</span></div>
</td>
<td width="16">
<div align="center"><span class="STYLE1">頁 </span></div>
</td>
<td width="45">
<a href="javascript:goPageByInput()"><img src="<%=contextPath%>/back/images/go.gif" width="37" height="15" /></a>
</td>
</tr>
</table>
</s:if>
<script type="text/javascript">
var totalPageSize=<s:property value="page.totalPageSize"/>;//總頁碼
function goPage(pageNum){
var pageNoReg = new RegExp("\\.currentPage=[0-9]*");
document.location="${servletRequestParms}".replace(pageNoReg,".currentPage=" + pageNum);
}
function goPageByInput() {
var pageNo = document.getElementById("pageNoIpt").value;
if(/^\d+$/.test(pageNo)==false) {
alert("只能輸入整數,請重新輸入!");
document.getElementById("pageNoIpt").value='';
return;
}
if(pageNo < 1) {
pageNo = 1;
}
if(pageNo > totalPageSize) {
if(totalPageSize>0)
pageNo = totalPageSize;
else
pageNo=1;
}
goPage(pageNo);
};
</script>