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。工程結構目錄如下:

Mybatis分頁



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 https://www.tw511.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 https://www.tw511.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  組態檔案裡最主要的組態:

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
	default-autowire="byName" default-lazy-init="false">

	<!--本範例採用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>
</beans> 
組態檔案 Configuration.xml 的內容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases> 
        <typeAlias alias="User" type="com.yiibai.pojo.User"/>
        <typeAlias alias="Order" type="com.yiibai.pojo.Order"/>  
    </typeAliases> 
    <!-- 與spring 整合之後,這些可以完全刪除,資料庫連線的管理交給 spring 去管理 -->
    <!-- 
	<environments default="development">
		<environment id="development">
		<transactionManager type="JDBC"/>
			<dataSource type="POOLED">
			<property name="driver" value="com.mysql.jdbc.Driver"/>
			<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8" />
			<property name="username" value="root"/>
			<property name="password" value="password"/>
			</dataSource>
		</environment>
	</environments>
	-->
	
	<!-- 這裡交給sqlSessionFactory 的 mapperLocations屬性去得到所有組態資訊 -->
	<!-- 
	<mappers>
	    <mapper resource="com/yihaomen/mapper/User.xml"/>
	</mappers>
	--> 
	
</configuration>

UserMaper.xml 用於定義查詢和資料物件對映,其內容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yiibai.maper.UserMaper">
	
		<!-- 為了返回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>    
</mapper>

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 ,顯示結果如下:

MyBatis分頁結果顯示


工程 mybatis08-paging 的程式碼下載:http://pan.baidu.com/s/1pJxhvNt

Jar 包下載:http://pan.baidu.com/s/1bnyRJ9H