Mybatis分页工具 PageHelper,Maven测试项目

来源:互联网 发布:mac电脑怎么弄VPN 编辑:程序博客网 时间:2024/06/10 02:12

5.0.0版本更新了..17/3/2


Mybatis分页工具 PageHelper

了解PageHelper https://github.com/pagehelper/Mybatis-PageHelper

对于Maven项目

只需要加入两个依赖包

        <dependency>            <groupId>com.github.pagehelper</groupId>            <artifactId>pagehelper</artifactId>            <version>4.2.1</version>        </dependency>        <dependency>            <groupId>com.github.jsqlparser</groupId>            <artifactId>jsqlparser</artifactId>            <version>0.9.5</version>        </dependency>

PageHelper 是一个拦截器,还需要配置调用这个拦截器,你可以配置在Mybatis的配置文件中,如果你把Mybatis写在了Spring的配置文件中,同样在spring的配置文件中,声明这个拦截器。具体配置在下面的文件中。

对于非 maven 项目

需要下载jar包,导入到工程中

下载JAR包

分页插件pagehelper.jar:

  • https://oss.sonatype.org/content/repositories/releases/com/github/pagehelper/pagehelper/

  • http://repo1.maven.org/maven2/com/github/pagehelper/pagehelper/

由于使用了sql解析工具,你还需要下载jsqlparser.jar

4.1.0及以后版本需要0.9.5版本

  • http://repo1.maven.org/maven2/com/github/jsqlparser/jsqlparser/0.9.5/

4.1.0以前版本需要0.9.1版本

  • http://repo1.maven.org/maven2/com/github/jsqlparser/jsqlparser/0.9.1/

我的 Maven 测试项目

Spring+Mybatis项目,通过Junit测试输出查询数据,不涉及SpringMVC前台页面。

这里写图片描述

源代码下载

版本信息

Eclipse版本 Neon.1a Release (4.6.1)apache-maven-3.3.9数据库 MySQL5.7.12

maven 配置的中央仓库阿里云地址

setting.xml

.. <mirrors>    <mirror>      <id>alimaven</id>      <name>aliyun maven</name>      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>      <mirrorOf>central</mirrorOf>            </mirror>  </mirrors>  .  .

创建MySQL数据表

建表语句和数据表内容

mysql> use db_ssm;Database changedmysql> CREATE TABLE tb_user(    -> id int(11) NOT NULL AUTO_INCREMENT,    -> user_name varchar(40) NOT NULL,    -> password varchar(40) NOT NULL,    -> age int(4) NOT NULL,    -> PRIMARY KEY(id))    -> ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;Query OK, 0 rows affected (0.33 sec)mysql> desc tb_user;+-----------+-------------+------+-----+---------+----------------+| Field     | Type        | Null | Key | Default | Extra          |+-----------+-------------+------+-----+---------+----------------+| id        | int(11)     | NO   | PRI | NULL    | auto_increment || user_name | varchar(40) | NO   |     | NULL    |                || password  | varchar(40) | NO   |     | NULL    |                || age       | int(4)      | NO   |     | NULL    |                |+-----------+-------------+------+-----+---------+----------------+4 rows in set (0.02 sec)mysql> select * from tb_user;+----+-----------+----------+-----+| id | user_name | password | age |+----+-----------+----------+-----+|  1 | 李白      | 123454   |  23 ||  2 | 杜甫2     | 234234   |  23 ||  6 | 杜甫3     | 234234   |  23 ||  7 | 李清照    | 3232322  |  22 ||  8 | 杜甫4     | 234234   |  23 ||  9 | 杜甫5     | 234234   |  23 |+----+-----------+----------+-----+

数据库连接配置信息

jdbc.properties

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/db_ssmusername=rootpassword=rootinitialSize=0 maxActive=20 maxIdle=20minIdle=1maxWait=60000

实体类User

User.java

package com.jxust.ssm.pojo;/** * 用户实体类 * 对应数据表tb_user * @author Peng * @Date2016年12月10日下午10:30:16 */public class User {    private Integer id;    private String userName;    private String password;    private Integer age;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName == null ? null : userName.trim();    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password == null ? null : password.trim();    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    @Override    public String toString() {        return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]";    }   }

Dao 层UserDao

UserDao.java

package com.jxust.ssm.dao;import java.util.List;import com.jxust.ssm.pojo.User;/** * User类Dao层接口 *  * 之前我们会在dao层自己手动实现dao层接口然后自动注入SqlSessionTemplate 实例 * 来调用具体的方法 比如 insert("","")  selectOne("","") 等方法  * 其中第一个参数就是映射文件的地址: namespace+id  而第二个参数就是传递的条件这样mybatis  * 就会按照我们传递的这两个参数找到具体的映射文件进行解析查询。 * 而这里使用动态代理就省去了我们实现dao接口的这一步骤,而是由spring提我们实现了 * @author Peng * @Date2016年12月10日下午10:31:27 */public interface UserDao {    int deleteByPrimaryKey(Integer id);    int insert(User record);    int insertSelective(User record);    User selectByPrimaryKey(Integer id);    int updateByPrimaryKeySelective(User record);    int updateByPrimaryKey(User record);    /**     * 查询所有数据,分页时用到这个     * @return     */    List<User> selectUserList();}

Mybatis映射文件UserMapper.xml

分页只用到查询所有数据的这个 selectUserList select 方法,这里其他方法我没有删除

UserMapper.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" ><!-- namespace的值就是dao接口的完整路径,就这个demo而言namespace 就是userDao.java的完整路径--><mapper namespace="com.jxust.ssm.dao.UserDao">    <resultMap id="BaseResultMap" type="com.jxust.ssm.pojo.User">        <id column="id" property="id" jdbcType="INTEGER" />        <result column="user_name" property="userName" jdbcType="VARCHAR" />        <result column="password" property="password" jdbcType="VARCHAR" />        <result column="age" property="age" jdbcType="INTEGER" />    </resultMap>    <sql id="Base_Column_List">        id, user_name, password, age    </sql>    <select id="selectByPrimaryKey" resultMap="BaseResultMap"        parameterType="java.lang.Integer">        select        <include refid="Base_Column_List" />        from tb_user        where id = #{id,jdbcType=INTEGER}    </select>    <!--查询所有数据 -->    <select id="selectUserList" resultMap="BaseResultMap">        select        <include refid="Base_Column_List" />        from tb_user    </select>    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">        delete from        tb_user        where id = #{id,jdbcType=INTEGER}    </delete>    <insert id="insert" parameterType="com.jxust.ssm.pojo.User">        insert into tb_user (id,        user_name, password,        age)        values (#{id,jdbcType=INTEGER},        #{userName,jdbcType=VARCHAR},        #{password,jdbcType=VARCHAR},        #{age,jdbcType=INTEGER})    </insert>    <insert id="insertSelective" parameterType="com.jxust.ssm.pojo.User">        insert into tb_user        <trim prefix="(" suffix=")" suffixOverrides=",">            <if test="id != null">                id,            </if>            <if test="userName != null">                user_name,            </if>            <if test="password != null">                password,            </if>            <if test="age != null">                age,            </if>        </trim>        <trim prefix="values (" suffix=")" suffixOverrides=",">            <if test="id != null">                #{id,jdbcType=INTEGER},            </if>            <if test="userName != null">                #{userName,jdbcType=VARCHAR},            </if>            <if test="password != null">                #{password,jdbcType=VARCHAR},            </if>            <if test="age != null">                #{age,jdbcType=INTEGER},            </if>        </trim>    </insert>    <update id="updateByPrimaryKeySelective" parameterType="com.jxust.ssm.pojo.User">        update tb_user        <set>            <if test="userName != null">                user_name = #{userName,jdbcType=VARCHAR},            </if>            <if test="password != null">                password = #{password,jdbcType=VARCHAR},            </if>            <if test="age != null">                age = #{age,jdbcType=INTEGER},            </if>        </set>        where id = #{id,jdbcType=INTEGER}    </update>    <update id="updateByPrimaryKey" parameterType="com.jxust.ssm.pojo.User">        update tb_user        set        user_name = #{userName,jdbcType=VARCHAR},        password =        #{password,jdbcType=VARCHAR},        age = #{age,jdbcType=INTEGER}        where id =        #{id,jdbcType=INTEGER}    </update></mapper>

日志格式配置文件

lo4j.properties

 log4j.rootLogger=INFO,Console,File  #\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0  log4j.appender.Console=org.apache.log4j.ConsoleAppender  log4j.appender.Console.Target=System.out  #\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F  log4j.appender.Console.layout = org.apache.log4j.PatternLayout  log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  #\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6  log4j.appender.File = org.apache.log4j.RollingFileAppender  #\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55  log4j.appender.File.File = logs/ssm.log  #\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F  log4j.appender.File.MaxFileSize = 10MB  # \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7  log4j.appender.File.Threshold = ALL  log4j.appender.File.layout = org.apache.log4j.PatternLayout  log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n  

Mybatis配置文件

如果你是使用这个文件单独配置Mybatis,引用这个PageHelper,就写在mybatis-config.xml文件中,在spring配置文件中(在SqlSessionFactoryBean中)应用。
如果你集成在Spring中,那就写在Spring配置文件中

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- 配置PageHelper拦截器插件 -->  <plugins>    <!-- com.github.pagehelper为PageHelper类所在包名 -->    <plugin interceptor="com.github.pagehelper.PageHelper">        <!-- 4.0.0以后版本可以不设置该参数 -->        <property name="dialect" value="mysql"/>        <!-- 该参数默认为false -->        <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->        <!-- 和startPage中的pageNum效果一样-->        <property name="offsetAsPageNum" value="true"/>        <!-- 该参数默认为false -->        <!-- 设置为true时,使用RowBounds分页会进行count查询 -->        <property name="rowBoundsWithCount" value="true"/>        <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->        <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->        <property name="pageSizeZero" value="true"/>        <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->        <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->        <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->        <property name="reasonable" value="false"/>        <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->        <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->        <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置映射的用默认值 -->        <!-- 不理解该含义的前提下,不要随便复制该配置 -->        <property name="params" value="pageNum=pageHelperStart;pageSize=pageHelperRows;"/>        <!-- 支持通过Mapper接口参数来传递分页参数 -->        <property name="supportMethodsArguments" value="false"/>        <!-- always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page -->        <property name="returnPageInfo" value="none"/>    </plugin></plugins></configuration>

Spirng 配置文件

spring-mybatis.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:context="http://www.springframework.org/schema/context"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">    <!-- 自动扫描 -->      <context:component-scan base-package="com.jxust.ssm" >    <!-- 不扫描@Controller注解的类-->        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>    </context:component-scan>        <!-- 引入配置文件 -->      <bean id="propertyConfigurer"          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">          <property name="location" value="classpath:jdbc.properties" />      </bean>      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"          destroy-method="close">          <property name="driverClassName" value="${driver}" />          <property name="url" value="${url}" />          <property name="username" value="${username}" />          <property name="password" value="${password}" />          <!-- 初始化连接大小 -->          <property name="initialSize" value="${initialSize}"></property>          <!-- 连接池最大数量 -->          <property name="maxActive" value="${maxActive}"></property>          <!-- 连接池最大空闲 -->          <property name="maxIdle" value="${maxIdle}"></property>          <!-- 连接池最小空闲 -->          <property name="minIdle" value="${minIdle}"></property>          <!-- 获取连接最大等待时间 -->          <property name="maxWait" value="${maxWait}"></property>      </bean>       <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 -->      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <property name="dataSource" ref="dataSource" />          <!-- 自动扫描mapping.xml文件 -->          <property name="mapperLocations" value="classpath:com/jxust/ssm/mapping/*.xml"></property>         <!-- 引入Mybatis配置文件 -->        <property name="configLocation" value="classpath:mybatis-config.xml"></property>    </bean>      <!-- DAO接口所在包名,Spring会自动查找其下的类 动态代理实现 不用写dao的实现类-->      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">          <property name="basePackage" value="com.jxust.ssm.dao" />          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>      </bean>      <!-- (事务管理)transaction manager-->      <bean id="transactionManager"          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">          <property name="dataSource" ref="dataSource" />      </bean>      <tx:annotation-driven transaction-manager="transactionManager"/></beans>

如果你的Mybatis配置在spring配置文件中,可以使用spring配置方式配置PageHelper,同样在SqlSessionFactoryBean这个bean中配置,这个时候,就不需要引入mybatis-config.xml配置文件(如果你有的话),同时配置两个会有异常!

 <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 -->      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <property name="dataSource" ref="dataSource" />          <!-- 自动扫描mapping.xml文件 -->          <property name="mapperLocations" value="classpath:com/jxust/ssm/mapping/*.xml"></property>        <property name="plugins">            <array>                <bean class="com.github.pagehelper.PageHelper">                    <property name="properties" >                        <value>                            dialect=mysql                            offsetAsPageNum=true                            rowBoundsWithCount=true                            pageSizeZero=truereasonable=false                            reasonable=true                            params=pageNum=pageHelperStart;pageSize=pageHelperRows;                            supportMethodsArguments=false                        </value>                    </property>                </bean>            </array>        </property>     </bean>  

注意:请不用同时使用spring配置方式和mybatis-config.xml配置方式,只需要选择其中一个就行。配置多个分页插件时,会抛出异常提示。

测试分页效果

Spring方式

TestMyBatis.java

package com.test;import java.util.List;import javax.annotation.Resource;import org.apache.log4j.Logger;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.alibaba.fastjson.JSON;import com.github.pagehelper.PageHelper;import com.jxust.ssm.dao.UserDao;import com.jxust.ssm.pojo.User;@RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })/** * 测试spring整合mybatis  *  * @author Peng * @Date2016年12月11日上午11:52:56 */public class TestMyBatis {    private static Logger logger = Logger.getLogger(TestMyBatis.class);    @Resource    private UserDao userDao;    @Test    public void test1() {        User user = userDao.selectByPrimaryKey(1);        logger.info("值:" + user.getUserName());        logger.info(JSON.toJSONString(user));    }    //测试分页效果    @Test    public void testPage(){        //每页显示3条数据,显示第二页        PageHelper.startPage(2, 3);        List<User> lists = userDao.selectUserList();        for(User u:lists){            System.out.println(u.toString());        }    }}

数据库的数据为:

+----+-----------+----------+-----+| id | user_name | password | age |+----+-----------+----------+-----+|  1 | 李白      | 123454   |  23 ||  2 | 杜甫2     | 234234   |  23 ||  6 | 杜甫3     | 234234   |  23 ||  7 | 李清照    | 3232322  |  22 ||  8 | 杜甫4     | 234234   |  23 ||  9 | 杜甫5     | 234234   |  23 |+----+-----------+----------+-----+

执行testPage方法,此时的分页条件为PageHelper.startPage(2, 3);输出如下:

这里写图片描述

更换分页条件PageHelper.startPage(1, 4);

这里写图片描述

只有紧跟着分页条件的第一个select方法会被分页

例如:

      @Test    public void testPage(){        PageHelper.startPage(1, 4);        List<User> lists = userDao.selectUserList();        for(User u:lists){            System.out.println(u.toString());        }        System.out.println("----------大闹天宫的分隔线----------------");        List<User> lists2 = userDao.selectUserList();        for(User u:lists2){            System.out.println(u.toString());        }    }

这里写图片描述

普通的Junit测试方法

和上面方法一样,只是获取对象的方式不同而已

TestMybatis2.java

package com.test;import java.util.List;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.github.pagehelper.PageHelper;import com.jxust.ssm.dao.UserDao;import com.jxust.ssm.pojo.User;/** * 测试spring整合mybatis * @author Peng * @Date2016年12月11日上午11:52:11 */public class TestMyBatis2 {    private ApplicationContext ac = null;    private UserDao userDao;    @Before    public void before() {        ac = new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml");            userDao = (UserDao) ac.getBean("userDao");    }    @Test    public void test2() {        User user = userDao.selectByPrimaryKey(2);        System.out.println(user.toString());    }    @Test    public void testPage() {        PageHelper.startPage(2, 3);        List<User> lists = userDao.selectUserList();        for(User u:lists){            System.out.println(u.toString());        }    }}

源代码下载

http://download.csdn.net/detail/peng_hong_fu/9712139

0 0