来自棱镜学院-在线IT教育www.prismcollege.com
分页方法一:
可以查看如下代码,新建一个数据库分页基础类
package com.ssm.utils.pagination.pagebounds;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
public class BasePageService {
@Autowired
private SqlSessionFactoryBean sqlSessionFactoryBean;
public List> getPageList(Class> mapperClass, String sqlId,
Object sqlParameter, int pageIndex, int pageSize) {
SqlSession session = null ;
try {
SqlSessionFactory sessionFactory = sqlSessionFactoryBean
.getObject();
session = sessionFactory.openSession();
if (pageIndex <= 0 ) {
pageIndex = 1 ;
}
if (pageSize <= 0 ) {
pageSize = 10 ;
}
PageBounds pageBounds = new PageBounds(pageIndex, pageSize);
List pageList = session.selectList(mapperClass.getName()
+ "." + sqlId, sqlParameter, pageBounds);
return pageList;
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return null ;
}
}
分页方法2:
定义一个page基本类,用于网页与后端之间的页面传输封装
下面这个类PageData为扩展使用,目前暂未使用
接下来可根据page定义一个更加具体的页面和后端传输的页面封装类,如
import java.io.Serializable;
import java.util.List;
public class XXXPage extends Page implements Serializable{
private String identity_type;
private String username;
private String name;
private String city;
private List freeTimeList;
private String[] jobType;
private List createdTimeList;
********************************
public String getIdentity_type() {
return identity_type;
}
public void setIdentity_type(String identity_type) {
this .identity_type = identity_type;
}
}
下一步可在controller的action中使用 如
public String listPageData(Model model, XXXPage page,HttpServletRequest request) {
xxxxxxxxx;
} 并在传回客户端时可 model.addAttribute("page", page);
其中 mybatis中操作
List list = userMapper.findXXXByPage(page);//得到满足条件的招聘用户列表 int rows = xxxMapper.findRows(page);//得到满足条件的行数
page.setRows(rows);
只需要在mapper中sql中 进行sql分页 limit #{begin,jdbcType=INTEGER},#{showCount,jdbcType=INTEGER} 即可。
分页方法3:
修改mybatis自带的rowbound内存分页为物理分页
新建类Page_duan
新建如下类
import java.util.Properties;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathNotFoundException;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.parameter.DefaultParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.MappedStatement.Builder;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
@Intercepts ({ @Signature (type=Executor. class ,method= "query" ,
args={ MappedStatement.class , Object. class , RowBounds. class , ResultHandler. class })})
public class PageHelper_duan implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement=(MappedStatement)invocation.getArgs()[0 ];
Object parameter = invocation.getArgs()[1 ];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String originalSql = boundSql.getSql().trim();
Object parameterObject = boundSql.getParameterObject();
Page_duan page = searchPageWithXpath(boundSql.getParameterObject(),"." , "page" , "*/page" );
if (page!= null ){
String countSql = getCountSql(originalSql);
Connection connection=mappedStatement.getConfiguration()
.getEnvironment().getDataSource().getConnection() ;
PreparedStatement countStmt = connection.prepareStatement(countSql);
BoundSql countBS = copyFromBoundSql(mappedStatement, boundSql, countSql);
DefaultParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, countBS);
parameterHandler.setParameters(countStmt);
ResultSet rs = countStmt.executeQuery();
int totpage= 0 ;
if (rs.next()) {
totpage = rs.getInt(1 );
}
rs.close();
countStmt.close();
connection.close();
page.setTotalRecord(totpage);
int offset = (page.getPageNo() - 1 ) * page.getPageSize();
StringBuffer sb = new StringBuffer();
sb.append(originalSql).append(" limit " ).append(offset).append( "," ).append(page.getPageSize());
BoundSql newBoundSql = copyFromBoundSql(mappedStatement, boundSql, sb.toString());
MappedStatement newMs = copyFromMappedStatement(mappedStatement,new BoundSqlSqlSource(newBoundSql));
invocation.getArgs()[0 ]= newMs;
}
return invocation.proceed();
}
private Page_duan searchPageWithXpath(Object o,String... xpaths) {
JXPathContext context = JXPathContext.newContext(o);
Object result;
for (String xpath : xpaths){
try {
result = context.selectSingleNode(xpath);
} catch (JXPathNotFoundException e) {
continue ;
}
if ( result instanceof Page_duan ){
return (Page_duan)result;
}
}
return null ;
}
private MappedStatement copyFromMappedStatement(MappedStatement ms,SqlSource newSqlSource) {
Builder builder = new Builder(ms.getConfiguration(),ms.getId(),newSqlSource,ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
for (String pro : ms.getKeyProperties())
builder.keyProperty(pro);
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
private BoundSql copyFromBoundSql(MappedStatement ms, BoundSql boundSql, String sql) {
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
for (ParameterMapping mapping : boundSql.getParameterMappings()) {
String prop = mapping.getProperty();
if (boundSql.hasAdditionalParameter(prop)) {
newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
}
}
return newBoundSql;
}
private String getCountSql(String sql) {
return "SELECT COUNT(*) FROM (" + sql + ") aliasForPage" ;
}
public class BoundSqlSqlSource implements SqlSource {
BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this .boundSql = boundSql;
}
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
@Override
public Object plugin(Object arg0) {
return Plugin.wrap(arg0, this );
}
@Override
public void setProperties(Properties arg0) {
}
}
java,架构技术学习 欢迎加QQ群交流:
368614849
14