我是靠谱客的博主 复杂小鸽子,最近开发中收集的这篇文章主要介绍MyBatis使用PageHelper实现分页,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

MyBatis分页

在JavaWeb中,使用JDBC的方式实现数据的分页,主要实现的原理:在查询的语句后面添加 (limit) 关键字,然后实现查询的数据分页功能。但是如果需要在所有的查询中都添加分页的话,那么就需要在所有的select语句后面添加 (limit) 关键字,这样的工作量是巨大的。同时也要改动大量的代码。
mybatis中提供的插件(plugin)机制,运行在mybatis的原有的处理逻辑上添加一些额外的逻辑,这样既不需要修改原来的代码,而且还可以非常容易进行实现。mybatis的插件机制,本质就拦截指定的查询操作,然后在查询的操作添加相关的分页逻辑。
使用PageHelper实现分页
1.创建数据库表:

create table tb_user(
userid int primary key auto_increment,
username varchar(20),
userage int,
useraddress varchar(30)
);

2.添加所需依赖:

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <!-- 配置分页依赖 -->
    <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>

3.创建 UserBean实体类:

package qing.bean;
public class UserBean {
    private int userid;
    private String username;
    private int userage;
    private String useraddress;

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getUserage() {
        return userage;
    }

    public void setUserage(int userage) {
        this.userage = userage;
    }

    public String getUseraddress() {
        return useraddress;
    }

    public void setUseraddress(String useraddress) {
        this.useraddress = useraddress;
    }
}

4.创建 UserMapper 接口:

package qing.mapper;
import qing.bean.UserBean;
import java.util.List;
public interface UserMapper {
    //批量添加
    boolean insertUser(List<UserBean> userBeanList);

    //查询所有
    List<UserBean> selectUserAll();
}

5.创建 mydata.properties 数据库资源文件:

mydriver = com.mysql.jdbc.Driver
myurl = jdbc:mysql://127.0.0.1:3306/test
myusername = root
mypassword = 123456

6.创建 UserMapper .xml接口SQL映射文件:

<?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="qing.mapper.UserMapper">
    <insert id="insertUser" parameterType="java.util.List">
        insert into tb_user values
        <foreach collection="list" item="user" separator=",">
            (null,#{user.username},#{user.userage},#{user.useraddress})
        </foreach>
    </insert>
    <resultMap id="userMap" type="UserBean">
        <id column="userid" property="userid"></id>
        <result column="username" property="username"></result>
        <result column="userage" property="userage"></result>
        <result column="useraddress" property="useraddress"></result>
    </resultMap>
    <select id="selectUserAll" resultMap="userMap">
        select * from tb_user
    </select>
</mapper>

7.创建 mybatis-config.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>
    <!-- 引入数据库资源文件 -->
    <properties resource="mydata.properties"></properties>
    <!-- 配置别名 -->
    <typeAliases>
        <typeAlias type="qing.bean.UserBean"></typeAlias>
    </typeAliases>
    <!-- 配置分页插件的拦截器 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 配置方言,使用的是那个库  ,在PageHelper5.0之后 不需要配置-->
            <!--  <property name="dialect" value="mysql"/> -->
        </plugin>
    </plugins>
    <!-- 配置数据库连接 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${mydriver}"></property>
                <property name="url" value="${myurl}"></property>
                <property name="username" value="${myusername}"></property>
                <property name="password" value="${mypassword}"></property>
            </dataSource>
        </environment>
    </environments>
    <!-- 引入接口SQL映射文件 -->
    <mappers>
        <mapper resource="UserMapper.xml"></mapper>
    </mappers>
</configuration>

8.创建测试类:

package qing.test;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import qing.bean.UserBean;
import qing.mapper.UserMapper;
import java.util.ArrayList;
import java.util.List;
public class TestMain {

    /**
     * 批量循环添加测试数据
     *
     * @return
     */
    public static List<UserBean> getData() {
        List<UserBean> userBeanList = new ArrayList<UserBean>();
        for (int i = 1; i <= 100; i++) {
            UserBean userBean = new UserBean();
            userBean.setUsername("hello-" + i);
            userBean.setUserage(9 + i);
            userBean.setUseraddress("中国--" + i);
            userBeanList.add(userBean);
        }
        return userBeanList;
    }

    /**
     * 添加测试数据
     */
    public static void insertUser() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            boolean flag = userMapper.insertUser(getData());
            if (flag == true) {
                System.out.println("添加成功!!!");
            } else {
                System.out.println("添加失败!");
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 分页查询数据
     */
    public static void selectPage() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //设置分页参数,起始页和每页记录数
            PageHelper.startPage(3, 5);
            List<UserBean> userBeanList = userMapper.selectUserAll();
            PageInfo<UserBean> pageInfo = new PageInfo<UserBean>(userBeanList);
            sqlSession.commit();
            System.out.println("当前页=" + pageInfo.getPageNum());
            System.out.println("每页数=" + pageInfo.getPageSize());
            System.out.println("当前页数=" + pageInfo.getSize());
            System.out.println("总记录数=" + pageInfo.getTotal());
            System.out.println("总页数=" + pageInfo.getPages());
            //得到当前页结果集合
            List<UserBean> userlist = pageInfo.getList();
            for (UserBean userBean : userlist) {
                System.out.println(userBean.getUserid() + "t" + userBean.getUsername()
                        + "t" + userBean.getUserage() + "t" + userBean.getUseraddress());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    public static void main(String[] args) {
        //insertUser();
        selectPage();
    }
}

9.结果:
在这里插入图片描述

最后

以上就是复杂小鸽子为你收集整理的MyBatis使用PageHelper实现分页的全部内容,希望文章能够帮你解决MyBatis使用PageHelper实现分页所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(37)

评论列表共有 0 条评论

立即
投稿
返回
顶部