MyBatis分頁
搞清楚什麼是分頁(pagination)
例如,在數據庫的某個表裏有1000條數據,我們每次只顯示100條數據,在第1頁顯示第0到第99條,在第2頁顯示第100到199條,依次類推,這就是分頁。
分頁可以分爲邏輯分頁和物理分頁。邏輯分頁是我們的程序在顯示每頁的數據時,首先查詢得到表中的1000條數據,然後成熟根據當前頁的「頁碼」選出其中的100條數據來顯示。
物理分頁是程序先判斷出該選出這1000條的第幾條到第幾條,然後數據庫根據程序給出的信息查詢出程序需要的100條返回給我們的程序。
MyBatis 物理分頁
MyBatis使用RowBounds實現的分頁是邏輯分頁,也就是先把數據記錄全部查詢出來,然在再根據 offset 和 limit 截斷記錄返回。
爲了在數據庫層面上實現物理分頁,又不改變原來 MyBatis 的函數邏輯,可以編寫 plugin 截獲 MyBatis Executor 的 statementhandler,重寫SQL來執行查詢。
經常搭框架的人應該都清楚,框架搭建的核心就是配置文件。
在這裏我們需要創建 web 工程。也需要用 mybatis與Spring mvc 集成起來,源碼在本文結尾處下載,主要有以下幾個方面的配置。
整個Mybatis分頁示例要完成的步驟如下:
1、示例功能描述
2、創建工程
3、數據庫表結構及數據記錄
4、實例對象
5、配置文件
6、測試執行,輸出結果
1、示例功能描述
在本示例中,需要使用 MyBatis和Spring MVC整合完成分頁,完成這樣的一個簡單功能,即指定一個用戶(ID=1),查詢出這個用戶關聯的所有訂單分頁顯示出來(使用的數據庫是:MySQL)。
2、創建工程
首先創建一個工程的名稱爲:mybatis08-paging,在 src 源代碼目錄下建立文件夾 config,並將原來的 mybatis 配置文件 Configuration.xml 移動到這個文件夾中, 並在 config 文家夾中建立 Spring 配置文件:applicationContext.xml。工程結構目錄如下:
3、數據庫表結構及數據記錄
在本示例中,用到兩個表:用戶表和訂單表,其結構和數據記錄如下:
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(64) NOT NULL DEFAULT '',
`mobile` varchar(16) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- Records of user
INSERT INTO `user` VALUES ('1', 'yiibai', '13838009988');
INSERT INTO `user` VALUES ('2', 'saya', '13838009988');
訂單表結構和數據如下:
CREATE TABLE `order` (
`order_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL DEFAULT '0',
`order_no` varchar(16) NOT NULL DEFAULT '',
`money` float(10,2) unsigned DEFAULT '0.00',
PRIMARY KEY (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
-- Records of order
INSERT INTO `order` VALUES ('1', '1', '1509289090', '99.90');
INSERT INTO `order` VALUES ('2', '1', '1519289091', '290.80');
INSERT INTO `order` VALUES ('3', '1', '1509294321', '919.90');
INSERT INTO `order` VALUES ('4', '1', '1601232190', '329.90');
INSERT INTO `order` VALUES ('5', '1', '1503457384', '321.00');
INSERT INTO `order` VALUES ('6', '1', '1598572382', '342.00');
INSERT INTO `order` VALUES ('7', '1', '1500845727', '458.00');
INSERT INTO `order` VALUES ('8', '1', '1508458923', '1200.00');
INSERT INTO `order` VALUES ('9', '1', '1504538293', '2109.00');
INSERT INTO `order` VALUES ('10', '1', '1932428723', '5888.00');
INSERT INTO `order` VALUES ('11', '1', '2390423712', '3219.00');
INSERT INTO `order` VALUES ('12', '1', '4587923992', '123.00');
INSERT INTO `order` VALUES ('13', '1', '4095378812', '421.00');
INSERT INTO `order` VALUES ('14', '1', '9423890127', '678.00');
INSERT INTO `order` VALUES ('15', '1', '7859213249', '7689.00');
INSERT INTO `order` VALUES ('16', '1', '4598450230', '909.20');
4、實例對象
用戶表和訂單表分別對應兩個實例對象,分別是:User.java 和 Order.java,它們都在 com.yiibai.pojo 包中。
User.java代碼內容如下:
package com.yiibai.pojo;
import java.util.List;
/**
* @describe: User
* @author: Yiibai
* @version: V1.0
* @copyright http://www.yiibai.com
*/
public class User {
private int id;
private String username;
private String mobile;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
Order.java代碼內容如下:
package com.yiibai.pojo;
/**
* @describe: User - 訂單
* @author: Yiibai
* @version: V1.0
* @copyright http://www.yiibai.com
*/
public class Order {
private int orderId;
private String orderNo;
private float money;
private int userId;
private User user;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
}
5、配置文件
這個實例中有三個重要的配置文件,它們分別是:applicationContext.xml , Configuration.xml 以及 UserMaper.xml。
applicationContext.xml 配置文件裏最主要的配置:
<!--本示例採用DBCP連接池,應預先把DBCP的jar包複製到工程的lib目錄下。 -->
<context:property-placeholder location="classpath:/config/database.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://127.0.0.1:3306/yiibai?characterEncoding=utf8"
p:username="root" p:password="" p:maxActive="10" p:maxIdle="10">
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource屬性指定要用到的連接池-->
<property name="dataSource" ref="dataSource" />
<!--configLocation屬性指定mybatis的核心配置文件-->
<property name="configLocation" value="classpath:config/Configuration.xml" />
<!-- 所有配置的mapper文件 -->
<property name="mapperLocations" value="classpath\*:com/yiibai/mapepr/\*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.yiibai.maper" />
</bean>
配置文件 Configuration.xml 的內容如下:
<!-- 這裏交給sqlSessionFactory 的 mapperLocations屬性去得到所有配置信息 -->
<!--
<mappers>
<mapper resource="com/yihaomen/mapper/User.xml"/>
</mappers>
-->
UserMaper.xml 用於定義查詢和數據對象映射,其內容如下:
<!-- 爲了返回list 類型而定義的returnMap -->
<resultMap type="User" id="resultUser">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="mobile" property="mobile" />
</resultMap>
<!-- User 聯合 Order 查詢 方法的配置 (多對一的方式) -->
<resultMap id="resultUserOrders" type="Order">
<id property="orderId" column="order\_id" />
<result property="orderNo" column="order\_no" />
<result property="money" column="money" />
<result property="userId" column="user\_id" />
<association property="user" javaType="User">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="mobile" column="mobile" />
</association>
</resultMap>
<select id="getUserOrders" parameterType="int" resultMap="resultUserOrders">
SELECT u.\*,o.\* FROM \`user\` u, \`order\` o
WHERE u.id=o.user\_id AND u.id=#{id}
</select>
<select id="getUserById" resultMap="resultUser" parameterType="int">
SELECT \*
FROM user
WHERE id=#{id}
</select>
6、測試執行,輸出結果
我們創建一個控制器類在包 com.yiibai.controller 下,類的名稱爲:UserController.java,這裏新增了一個方法:pageList, 對應請求URL是 /orderpages,其代碼如下:
package com.yiibai.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.yiibai.maper.UserMaper;
import com.yiibai.pojo.Order;
import com.yiibai.util.Page;
// http://localhost:8080/mybatis08-paging/user/orders
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserMaper userMaper;
/\*\*
\* 某一個用戶下的所有訂單
\*
\* @param request
\* @param response
\* @return
\*/
@RequestMapping("/orders")
public ModelAndView listall(HttpServletRequest request,
HttpServletResponse response) {
List<Order> orders = userMaper.getUserOrders(1);
System.out.println("orders");
ModelAndView mav = new ModelAndView("user\_orders");
mav.addObject("orders", orders);
return mav;
}
/\*\*
\* 訂單分頁
\*
\* @param request
\* @param response
\* @return
\*/
@RequestMapping("/orderpages")
public ModelAndView pageList(HttpServletRequest request,
HttpServletResponse response) {
int currentPage = request.getParameter("page") == null ? 1 : Integer
.parseInt(request.getParameter("page"));
int pageSize = 3;
if (currentPage <= 0) {
currentPage = 1;
}
int currentResult = (currentPage - 1) \* pageSize;
System.out.println(request.getRequestURI());
System.out.println(request.getQueryString());
Page page = new Page();
page.setShowCount(pageSize);
page.setCurrentResult(currentResult);
List<Order> orders = userMaper.getOrderListPage(page, 1);
System.out.println("Current page =>" + page);
int totalCount = page.getTotalResult();
int lastPage = 0;
if (totalCount % pageSize == 0) {
lastPage = totalCount % pageSize;
} else {
lastPage = 1 + totalCount / pageSize;
}
if (currentPage >= lastPage) {
currentPage = lastPage;
}
String pageStr = "";
pageStr = String.format(
"<a href=\\"%s\\">上一頁</a> <a href=\\"%s\\">下一頁</a>", request
.getRequestURI()
+ "?page=" + (currentPage - 1), request.getRequestURI()
+ "?page=" + (currentPage + 1));
// 制定視圖,也就是list.jsp
ModelAndView mav = new ModelAndView("pagelist");
mav.addObject("orders", orders);
mav.addObject("pagelist", pageStr);
return mav;
}
}
注意,在這個分頁工程中,在 com.yiibai.util 包下新增了幾個類,它們分別是:PagePlugin.java,Page.java, PageHelper.java,其中 PagePlugin 是針對 MyBatis 分頁的插件。由於代碼太多,這裏列出 PagePlugin.java 的代碼,其它兩個類的代碼有興趣的讀者可以在下載代碼後閱讀取研究。 PagePlugin.java 的代碼如下所示:
package com.yiibai.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.xml.bind.PropertyException;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
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.plugin.Signature;
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.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
@Intercepts( { @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class PagePlugin implements Interceptor {
private static String dialect = "";
private static String pageSqlId = "";
@SuppressWarnings("unchecked")
public Object intercept(Invocation ivk) throws Throwable {
if (ivk.getTarget() instanceof RoutingStatementHandler) {
RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk
.getTarget();
BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper
.getValueByFieldName(statementHandler, "delegate");
MappedStatement mappedStatement = (MappedStatement) ReflectHelper
.getValueByFieldName(delegate, "mappedStatement");
if (mappedStatement.getId().matches(pageSqlId)) {
BoundSql boundSql = delegate.getBoundSql();
Object parameterObject = boundSql.getParameterObject();
if (parameterObject == null) {
throw new NullYiibaierException("parameterObject error");
} else {
Connection connection = (Connection) ivk.getArgs()\[0\];
String sql = boundSql.getSql();
String countSql = "select count(0) from (" + sql
+ ") myCount";
System.out.println("總數sql 語句:" + countSql);
PreparedStatement countStmt = connection
.prepareStatement(countSql);
BoundSql countBS = new BoundSql(mappedStatement
.getConfiguration(), countSql, boundSql
.getParameterMappings(), parameterObject);
setParameters(countStmt, mappedStatement, countBS,
parameterObject);
ResultSet rs = countStmt.executeQuery();
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
countStmt.close();
Page page = null;
if (parameterObject instanceof Page) {
page = (Page) parameterObject;
page.setTotalResult(count);
} else if (parameterObject instanceof Map) {
Map<String, Object> map = (Map<String, Object>) parameterObject;
page = (Page) map.get("page");
if (page == null)
page = new Page();
page.setTotalResult(count);
} else {
Field pageField = ReflectHelper.getFieldByFieldName(
parameterObject, "page");
if (pageField != null) {
page = (Page) ReflectHelper.getValueByFieldName(
parameterObject, "page");
if (page == null)
page = new Page();
page.setTotalResult(count);
ReflectHelper.setValueByFieldName(parameterObject,
"page", page);
} else {
throw new NoSuchFieldException(parameterObject
.getClass().getName());
}
}
String pageSql = generatePageSql(sql, page);
System.out.println("page sql:" + pageSql);
ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql);
}
}
}
return ivk.proceed();
}
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());
}
}
}
}
private String generatePageSql(String sql, Page page) {
if (page != null && (dialect != null || !dialect.equals(""))) {
StringBuffer pageSql = new StringBuffer();
if ("mysql".equals(dialect)) {
pageSql.append(sql);
pageSql.append(" limit " + page.getCurrentResult() + ","
+ page.getShowCount());
} else if ("oracle".equals(dialect)) {
pageSql
.append("select \* from (select tmp\_tb.\*,ROWNUM row\_id from (");
pageSql.append(sql);
pageSql.append(") tmp\_tb where ROWNUM<=");
pageSql.append(page.getCurrentResult() + page.getShowCount());
pageSql.append(") where row\_id>");
pageSql.append(page.getCurrentResult());
}
return pageSql.toString();
} else {
return sql;
}
}
public Object plugin(Object arg0) {
// TODO Auto-generated method stub
return Plugin.wrap(arg0, this);
}
public void setProperties(Properties p) {
dialect = p.getProperty("dialect");
if (dialect == null || dialect.equals("")) {
try {
throw new PropertyException("dialect property is not found!");
} catch (PropertyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pageSqlId = p.getProperty("pageSqlId");
if (dialect == null || dialect.equals("")) {
try {
throw new PropertyException("pageSqlId property is not found!");
} catch (PropertyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
接下來部署 mybatis08-paging 這個工程,啓動 tomcat ,打開瀏覽器輸入網址:http://localhost:8080/mybatis08-paging/user/orderpages ,顯示結果如下:
工程 mybatis08-paging 的代碼下載:http://pan.baidu.com/s/1pJxhvNt
Jar 包下載:http://pan.baidu.com/s/1bnyRJ9H