mybatis分页查询怎么做
一、内存分页,使用RowBounds类,但这种方式不推荐,基本不用,所以此方式集成省略。
二、自定义实现,代码量比较少,简单,比较灵活。以下为具体的集成步骤:
1、在User.xml中加入select节点,并组装分页SQ
mybatis怎么配置和调用分页功能存储过程
CREATE OR REPLACE PROCEDURE SP_OD_SEARCHREVERSE_BEGIN(v_pageNo number, –查询页码
v_pageSize number, –每页显示大小
v_status in VARCHAR2, –要获取的状态
v_resultCur out HF_CURSOR.CURSOR_TYPE) –获取记录集合
is
/************************************************************
************************************************************/
l_pageNo number(10);
l_pageSize number(10);
BEGIN
if v_pageSize is null or v_pageSize = 0 then
l_pageSize := 10;
else
l_pageSize := v_pageSize;
end if;
OPEN v_resultCur FOR
select xxxx, xxxx, xxxx, xxxx, xxxx
from (select r.xxx, f.xxx, f.xxx, f.xxx, f.xxx
from OD_1 r, OD_2 f, OD_3 o, CH_4 c
where r.xxx = f.xxx
order by r.xxxx asc
)
where rownum 《= l_pageSize;
–close v_resultCur; — 不能关闭
END;
create or replace package HF_CURSOR is
— Author : ADMINISTRATOR
— Created : 2011-5-23 10:03:47
— Purpose : FOR RETURN LIST
— Public type declarations
TYPE CURSOR_TYPE IS REF CURSOR; –定义游标
mybatis-plus分页查询时候拼接了两次limit
你好,很高兴回答你的问题。
你可以检查一下是否使用了分页的插件什么的。
然后在语句的配置中又做了分页。
如果有帮助到你,请点击采纳。
mybatis 自动生成分页怎么用
针对上述思路,首先在 demo.mybatis.model下面新建一个名为PagenateArgs的分页参数实体类与一个名为SortDirectionEnum的枚举 类,里面包含当前页面索引pageIndex, 当前页展示业务记录数pageSize, pageStart属性表示从第几条开始,(pageStart=pageIndex*pageSize)因为limit关键词用法是表示【limit 起始条数(不包含),取几条】,orderFieldStr排序字段,orderDirectionStr 排序方向,所以具体创建如下:
package david.mybatis.model;/* * 分页参数实体类 */public class PagenateArgs { private int pageIndex; private int pageSize; private int pageStart; private String orderFieldStr; private String orderDirectionStr; public PagenateArgs() { // TODO Auto-generated constructor stub } public PagenateArgs(int pageIndex, int pageSize, String orderFieldStr, String orderDirectionStr) { this.pageIndex = pageIndex; this.pageSize = pageSize; this.orderFieldStr = orderFieldStr; this.orderDirectionStr = orderDirectionStr; pageStart = pageIndex * pageSize; } public int getPageIndex() { return pageIndex; } public int getPageStart() { return pageStart; } public int getPageSize() { return pageSize; } public String orderFieldStr() { return orderFieldStr; } public String getOrderDirectionStr() { return orderDirectionStr; }}
package david.mybatis.model;/* * 排序枚举 */public enum SortDirectionEnum { /* * 升序 */ ASC, /* * 降序 */ DESC}
完成上面的步骤以后在IVisitorOperation接口类中继续添加一个方法public List getListByPagenate(PagenateArgs args),这次的分页其实也就是在这个的基础上稍加改动即可,IVisitorOperation接口类 改动后如下所示:
package david.mybatis.demo;import java.util.List;import david.mybatis.model.PagenateArgs;import david.mybatis.model.Visitor;import david.mybatis.model.VisitorWithRn;public interface IVisitorOperation { /* * 基础查询 */ public Visitor basicQuery(int id); /* * 添加访问者 */ public int add(Visitor visitor); /* * 删除访问者 */ public int delete(int id); /* * 更新访问者 */ public int update(Visitor visitor); /* * 查询访问者 */ public Visitor query(int id); /* * 查询List */ public List getList(); /* * 分页查询List */ public List getListByPagenate(PagenateArgs args); }
接下来改动VisitorMapper.xml配置文件了,新增一个节点id与参数类型参照前几章的方式配置好,如下此处新增的id就为getListByPagenate,配置好以后如下
insert into Visitor (Name, Email, Status, CreateTime) values (#{name}, #{email}, #{status}, #{createTime}) delete from Visitor where status》0 and id = #{id} update Visitor set Name = #{name}, Email=#{email}, Status=#{status} where id=#{id} and Status》0; select Id, Name, Email, Status, CreateTime from visitor where id=#{id} and Status》0 order by Id select * from visitor where id=#{id} and Status》0 order by Id select * from Visitor where status》0 select * from ( ) t limit #{pageStart}, #{pageSize} order by ${orderFieldStr} ${orderDirectionStr}
这里面的字段属性都是针对PagenateArgs参数类中的属性名,保持一致。
limit #{pageStart}, #{pageSize}
在DemoRun类中创建测试方法:
/* * 分页参数 */public static void queryVisitorListWithPagenate(int pageIndex, int pageSize, String orderField, String orderDire) { PagenateArgs args = new PagenateArgs(pageIndex, pageSize, orderField, orderDire); SqlSession session = MybatisUtils.getSqlSession(); IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class); List visitors = vOperation.getListByPagenate(args); for (Visitor visitor : visitors) { System.out.println(visitor); } MybatisUtils.closeSession(session); MybatisUtils.showMessages(CRUD_Enum.List, visitors.size());}
DemoRun.queryVisitorListWithPagenate(0, 100, “id“, SortDirectionEnum.DESC.toString());
运行后下测试结果,先按Id倒序排列,查的Visitor表一共有14条记录,
假设取在第2页取5条,执行下面也就是6-10条数据,这样传参数就行了
DemoRun.queryVisitorListWithPagenate(1, 5, “id“, SortDirectionEnum.DESC.toString());
问一个Mybatis分页问题,Page和PageInfo的区别
Page继承了ArrayList 所以实际上就是一个list 你可以看下Page的getResult()方法就知道了 public List《E》 getResult() {
return this;
}
springmvc mybatis怎么实现分页查询
1.封装分页Page类
package com.framework.common.page.impl;
import java.io.Serializable;
import com.framework.common.page.IPage;
/**
*
*
*
*/
public abstract class BasePage implements IPage, Serializable {
/**
*
*/
private static final long serialVersionUID = -3623448612757790359L;
public static int DEFAULT_PAGE_SIZE = 20;
private int pageSize = DEFAULT_PAGE_SIZE;
private int currentResult;
private int totalPage;
private int currentPage = 1;
private int totalCount = -1;
public BasePage(int currentPage, int pageSize, int totalCount) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalCount = totalCount;
}
public int getTotalCount() {
return this.totalCount;
}
public void setTotalCount(int totalCount) {
if (totalCount 《 0) {
this.totalCount = 0;
return;
}
this.totalCount = totalCount;
}
public BasePage() {
}
public int getFirstResult() {
return (this.currentPage – 1) * this.pageSize;
}
public void setPageSize(int pageSize) {
if (pageSize 《 0) {
this.pageSize = DEFAULT_PAGE_SIZE;
return;
}
this.pageSize = pageSize;
}
public int getTotalPage() {
if (this.totalPage 《= 0) {
this.totalPage = (this.totalCount / this.pageSize);
if ((this.totalPage == 0) || (this.totalCount % this.pageSize != 0)) {
this.totalPage += 1;
}
}
return this.totalPage;
}
public int getPageSize() {
return this.pageSize;
}
public void setPageNo(int currentPage) {
this.currentPage = currentPage;
}
public int getPageNo() {
return this.currentPage;
}
public boolean isFirstPage() {
return this.currentPage 《= 1;
}
public boolean isLastPage() {
return this.currentPage 》= getTotalPage();
}
public int getNextPage() {
if (isLastPage()) {
return this.currentPage;
}
return this.currentPage + 1;
}
public int getCurrentResult() {
this.currentResult = ((getPageNo() – 1) * getPageSize());
if (this.currentResult 《 0) {
this.currentResult = 0;
}
return this.currentResult;
}
public int getPrePage() {
if (isFirstPage()) {
return this.currentPage;
}
return this.currentPage – 1;
}
}
package com.framework.common.page.impl;
import java.util.List;
/**
*
*
*
*/
public class Page extends BasePage {
/**
*
*/
private static final long serialVersionUID = -970177928709377315L;
public static ThreadLocal《Page》 threadLocal = new ThreadLocal《Page》();
private List《?》 data;
public Page() {
}
public Page(int currentPage, int pageSize, int totalCount) {
super(currentPage, pageSize, totalCount);
}
public Page(int currentPage, int pageSize, int totalCount, List《?》 data) {
super(currentPage, pageSize, totalCount);
this.data = data;
}
public List《?》 getData() {
return data;
}
public void setData(List《?》 data) {
this.data = data;
}
}
2.封装分页插件
package com.framework.common.page.plugin;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import javax.xml.bind.PropertyException;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
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.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import com.framework.common.page.impl.Page;
import com.framework.common.utils.ReflectUtil;
/**
*
*
*
*/
@Intercepts({ @org.apache.ibatis.plugin.Signature(type = org.apache.ibatis.executor.statement.StatementHandler.class, method = “prepare“, args = { Connection.class }) })
public class PagePlugin implements Interceptor {
private String dialect = ““;
private String pageSqlId = ““;
@Override
public Object intercept(Invocation invocation) throws Throwable {
if (invocation.getTarget() instanceof RoutingStatementHandler) {
BaseStatementHandler delegate = (BaseStatementHandler) ReflectUtil
.getValueByFieldName(
(RoutingStatementHandler) invocation.getTarget(),
“delegate“);
MappedStatement mappedStatement = (MappedStatement) ReflectUtil
.getValueByFieldName(delegate,
“mappedStatement“);
Page page = Page.threadLocal.get();
if (page == null) {
page = new Page();
Page.threadLocal.set(page);
}
if (mappedStatement.getId().matches(“.*(“ + this.pageSqlId + “)$“) && page.getPageSize() 》 0) {
BoundSql boundSql = delegate.getBoundSql();
Object parameterObject = boundSql.getParameterObject();
String sql = boundSql.getSql();
String countSqlId = mappedStatement.getId().replaceAll(pageSqlId, “Count“);
MappedStatement countMappedStatement = null;
if (mappedStatement.getConfiguration().hasStatement(countSqlId)) {
countMappedStatement = mappedStatement.getConfiguration().getMappedStatement(countSqlId);
}
String countSql = null;
if (countMappedStatement != null) {
countSql = countMappedStatement.getBoundSql(parameterObject).getSql();
} else {
countSql = “SELECT COUNT(1) FROM (“ + sql + “) T_COUNT“;
}
int totalCount = 0;
PreparedStatement countStmt = null;
ResultSet resultSet = null;
try {
Connection connection = (Connection) invocation.getArgs();
countStmt = connection.prepareStatement(countSql);
BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);
setParameters(countStmt, mappedStatement, countBoundSql, parameterObject);
resultSet = countStmt.executeQuery();
if(resultSet.next()) {
totalCount = resultSet.getInt(1);
}
} catch (Exception e) {
throw e;
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
} finally {
if (countStmt != null) {
countStmt.close();
}
}
}
page.setTotalCount(totalCount);
ReflectUtil.setValueByFieldName(boundSql, “sql“, generatePageSql(sql,page));
}
}
return invocation.proceed();
}
/**
* 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
* @param ps
* @param mappedStatement
* @param boundSql
* @param parameterObject
* @throws SQLException
*/
private void setParameters(PreparedStatement ps,MappedStatement mappedStatement,BoundSql boundSql,Object parameterObject) throws SQLException {
ErrorContext.instance().activity(“setting parameters“).object(mappedStatement.getParameterMap().getId());
List《ParameterMapping》 parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
Configuration configuration = mappedStatement.getConfiguration();
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);
for (int i = 0; i 《 parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
PropertyTokenizer prop = new PropertyTokenizer(propertyName);
if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {
value = boundSql.getAdditionalParameter(prop.getName());
if (value != null) {
value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
}
} else {
value = metaObject == null ? null : metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
if (typeHandler == null) {
throw new ExecutorException(“There was no TypeHandler found for parameter “+ propertyName + “ of statement “+ mappedStatement.getId());
}
typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
}
}
}
}
/**
* 根据数据库方言,生成特定的分页sql
* @param sql
* @param page
* @return
*/
private String generatePageSql(String sql,Page page){
if(page!=null && StringUtils.isNotBlank(dialect)){
StringBuffer pageSql = new StringBuffer();
if(“mysql“.equals(dialect)){
pageSql.append(sql);
pageSql.append(“ LIMIT “+page.getCurrentResult()+“,“+page.getPageSize());
}else if(“oracle“.equals(dialect)){
pageSql.append(“SELECT * FROM (SELECT TMP_TB.*,ROWNUM ROW_ID FROM (“);
pageSql.append(sql);
pageSql.append(“) AS TMP_TB WHERE ROWNUM 《= “);
pageSql.append(page.getCurrentResult()+page.getPageSize());
pageSql.append(“) WHERE ROW_ID 》 “);
pageSql.append(page.getCurrentResult());
}
return pageSql.toString();
}else{
return sql;
}
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
try {
if (StringUtils.isEmpty(this.dialect = properties
.getProperty(“dialect“))) {
throw new PropertyException(“dialect property is not found!“);
}
if (StringUtils.isEmpty(this.pageSqlId = properties
.getProperty(“pageSqlId“))) {
throw new PropertyException(“pageSqlId property is not found!“);
}
} catch (PropertyException e) {
e.printStackTrace();
}
}
}
附上出处链接:http://www.jb51.net/article/71829.htm
求助贴,关于mybatis的分页插件pageHelper
使用方法 1. 引入分页插件 引入分页插件一共有下面2种方式,推荐使用Maven方式,这种方式方便更新。 1). 引入Jar包 如果你想使用本项目的jar包而不是直接引入类,你可以在这里下载各个版本的jar包
mybatis pagehelper支持where条件分页吗
mybatis中首先要在配置文件中配置一些东西,然后根据这些配置去创建一个会话工厂,再根据会话工厂创建会话,会话发出操作数据库的sql语句,然后通过执行器操作数据,再使用mappedStatement对数据进行封装,这就是整个mybatis框架的执行情况。那么mybatis的插件作用在哪一环节呢?它主要作用在Executor执行器与mappedeStatement之间,也就是说mybatis可以在插件中获得要执行的sql语句,在sql语句中添加limit语句,然后再去对sql进行封装,从而可以实现分页处理。
MyBatis怎样实现MySQL动态分页
在这些控件里要达到分页的效果,一般都会传2个参数,第一个是表示当前页的索 引(一般从0开始),第二个表示当前页展示多少条业务记录,然后将相应的参数传递给List《T》 getList(PagenateArgs args)方法,最终实现数据库中的分页时候可以使用limit关键词(针对mysql)进行分页,如果是oracle或者sql server他们都有自带的rownum函数可以使用。
针对上述思路,首先在 demo.mybatis.model下面新建一个名为PagenateArgs的分页参数实体类与一个名为SortDirectionEnum的枚举 类,里面包含当前页面索引pageIndex, 当前页展示业务记录数pageSize, pageStart属性表示从第几条开始,(pageStart=pageIndex*pageSize)因为limit关键词用法是表示【limit 起始条数(不包含),取几条】,orderFieldStr排序字段,orderDirectionStr 排序方向,所以具体创建如下:
package david.mybatis.model;
/*
* 分页参数实体类
*/
public class PagenateArgs {
private int pageIndex;
private int pageSize;
private int pageStart;
private String orderFieldStr;
private String orderDirectionStr;
public PagenateArgs() {
// TODO Auto-generated constructor stub
}
public PagenateArgs(int pageIndex, int pageSize, String orderFieldStr, String orderDirectionStr) {
this.pageIndex = pageIndex;
this.pageSize = pageSize;
this.orderFieldStr = orderFieldStr;
this.orderDirectionStr = orderDirectionStr;
pageStart = pageIndex * pageSize;
}
public int getPageIndex() {
return pageIndex;
}
public int getPageStart() {
return pageStart;
}
public int getPageSize() {
return pageSize;
}
public String orderFieldStr() {
return orderFieldStr;
}
public String getOrderDirectionStr() {
return orderDirectionStr;
}
}
package david.mybatis.model;
/*
* 排序枚举
*/
public enum SortDirectionEnum {
/*
* 升序
*/
ASC,
/*
* 降序
*/
DESC
}
完成上面的步骤以后在IVisitorOperation接口类中继续添加一个方法public List《Visitor》 getListByPagenate(PagenateArgs args),这次的分页其实也就是在这个的基础上稍加改动即可,IVisitorOperation接口类 改动后如下所示:
package david.mybatis.demo;
import java.util.List;
import david.mybatis.model.PagenateArgs;
import david.mybatis.model.Visitor;
import david.mybatis.model.VisitorWithRn;
public interface IVisitorOperation {
/*
* 基础查询
*/
public Visitor basicQuery(int id);
/*
* 添加访问者
*/
public int add(Visitor visitor);
/*
* 删除访问者
*/
public int delete(int id);
/*
* 更新访问者
*/
public int update(Visitor visitor);
/*
* 查询访问者
*/
public Visitor query(int id);
/*
* 查询List
*/
public List《Visitor》 getList();
/*
* 分页查询List
*/
public List《Visitor》 getListByPagenate(PagenateArgs args);
}
接下来改动VisitorMapper.xml配置文件了,新增一个《select》节点id与参数类型参照前几章的方式配置好,如下此处新增的id就为getListByPagenate,配置好以后如下
《?xml version=“1.0“ encoding=“UTF-8“?》
《!DOCTYPE mapper
PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN“
“
《if test=“pageStart》-1 and pageSize》-1“》
limit #{pageStart}, #{pageSize}
《/if》
在DemoRun类中创建测试方法:
/*
* 分页参数
*/
public static void queryVisitorListWithPagenate(int pageIndex, int pageSize, String orderField, String orderDire) {
PagenateArgs args = new PagenateArgs(pageIndex, pageSize, orderField, orderDire);
SqlSession session = MybatisUtils.getSqlSession();
IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);
List《Visitor》 visitors = vOperation.getListByPagenate(args);
for (Visitor visitor : visitors) {
System.out.println(visitor);
}
MybatisUtils.closeSession(session);
MybatisUtils.showMessages(CRUD_Enum.List, visitors.size());
}
DemoRun.queryVisitorListWithPagenate(0, 100, “id“, SortDirectionEnum.DESC.toString());
运行后下测试结果,先按Id倒序排列,查的Visitor表一共有14条记录,
假设取在第2页取5条,执行下面也就是6-10条数据,这样传参数就行了
DemoRun.queryVisitorListWithPagenate(1, 5, “id“, SortDirectionEnum.DESC.toString());
结果如下:
实现了一个分页逻辑.