0
点赞
收藏
分享

微信扫一扫

MyBatis06:分页插件、MyBatis配置文件中的标签

m逆光生长 2022-04-24 阅读 68

系列文章目录

MyBatis01:创建、运行、测试一个mybatis项目
MyBatis02:使用MyBatis查询数据
MyBatis03:嵌套查询、嵌套结果、延迟加载
MyBatis04:动态SQL
MyBatis05:类型转换器


文章目录


前言

本文继续介绍MyBatis框架下如何使用框架实现分页。以及对MyBatis配置文件中的一些标签进行了讲解。


一、分页插件

1. 分页插件的配置

1.1 引jar包

  1. 要添加的jar包
    在这里插入图片描述
  2. 将其复制到lib文件夹下
  3. 如果是向lib文件夹中新添加一些jar包,需要将原来的lib删除一下,然后在重新Add as Library。这样项目就可以识别lib文件夹下的jar包了。
    在这里插入图片描述

1.2 添加拦截器插件

在MyBatis的主配置文件夹下添加该拦截器插件。

<configuration>
	<plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
        	<!--使用的语言是mysql数据库语言-->
            <property name="dialect" value="mysql"/>
            <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
            <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
            <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据,不再正常范围内 -->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>
</configuration>

拦截器的作用:在某程序要执行之前先捕获该程序,对该程序执行一定的操作。

2. 分页插件的使用

使用分页插件后,查询总记录数和查询要显示的数据集合的工作就由分页插件来帮我们做。

2.1 StudentMapper.java

这个是根据条件查询学生信息,然后对查询到的数据集合进行分页

	// 通过分页插件实现分页
    List<Student> selectByPagePlug(Student student);

2.2 StudentMapper.xml

只需要查询到所有满足条件的数据集合即可

<select id="selectByPagePlug" resultMap="baseMap">
    select <include refid="Base_Column_List"></include> from student
    <where>
        <if test="name != null">
          name like concat("%",#{name},"%")
        </if>
        <if test="sex != null">
          and sex = #{sex}
        </if>
        <if test="birthday != null">
          and birthday = #{birthday}
        </if>
        <if test="age != null and age > 0">
          and age = #{age}
        </if>
        <if test="classid != null and classid > 0">
          and classid = #{classid}
        </if>
    </where>
  </select>

2.3 StudentService.java

通过分页插件 PageInfo 获取分页信息和查询到的数据集合

	// 通过分页插件实现分页
    PageInfo<Student> selectByPagePlug(Student student, int pageNum, int pageSize);

2.4 StudentServiceImpl

	@Override
    public PageInfo<Student> selectByPagePlug(Student student, int pageNum, int pageSize) {
        // 当调用dao层查询方法之前,必须先设置分页的相关信息,针对马上执行的下一条select语句进行分页
        // 先设置分页信息,再获取查询结果
        // PageHelper是一个拦截器,用于拦截紧邻的一条dao层语句,在执行查询之前,会先查询到总记录数,以及使用limit查询到指定条数据
        // id desc指定按什么字段以及排序规则,可写可不写
        PageHelper.startPage(pageNum, pageSize, "id desc");
        List<Student> students = this.studentMapper.selectByPagePlug(student);
        // PageInfo的作用是
        PageInfo<Student> pageInfo = new PageInfo<>(students);
        return pageInfo;
    }

2.5 StudentMapperTest

PageInfo 是分页插件类,包含分页的所有信息 。

插件属性 含义
pageNum 当前页
pageSize 每页的数量
size 当前页的数量
total 总记录数(在这里也就是查询到的用户总数)
pages 总页数 (这个页数也很好算,每页5条,总共有11条,需要3页才可以显示完)
orderBy 排序
startRow 当前页面第一个元素在数据库中的行号
endRow 当前页面最后一个元素在数据库中的行号
list 结果集
prePage 前一页
nextPage 下一页
isFirstPage 是否为第一页
isLastPage 是否为最后一页
hasPreviousPage 是否有前一页
hasNextPage 是否有下一页
navigatePages 导航页码数
navigatepageNums 所有导航页号
navigateFirstPage 导航第一页
navigateLastPage 导航最后一页
firstPage 第一页
lastPage 最后一页

这里再次说明一下 PageInfo 对象中同时包含着分页信息集合信息

	@Test
    public void selectByPagePlug() {
    	// 获取PageInfo对象
        PageInfo<Student> stusInfo = this.studentService.selectByPagePlug(new Student(), 2, 2);
        // 获取集合信息
        List<Student> students = stusInfo.getList();
        // 输出集合信息
        students.forEach((student)->{
            System.out.println(student.getId() + "\t" + student.getName());
        });
        // 输出分页信息
        System.out.println("总记录数:" + stusInfo.getTotal() + "\t总页数" + stusInfo.getPages() + "\t当前第"
                + stusInfo.getPageNum() + "页");
    }

2.6 拦截器的作用

PageHelper拦截器的作用:拦截紧邻的SQL语句,并对其进行一定的处理。

2.6.1 普通的查询语句

在这里插入图片描述
在这里插入图片描述
dao层的SQL语句是 select * from student
拦截器的第一个处理是:根据这个SQL语句,查询总记录数 select count(*) from student
拦截器的第二个处理是:根据这个SQL语句,查询要显示的集合数据 select * from student limit ?, ?

使用了分页插件后,我们只需要需要查询的SQL语句即可,记录总数和要显示的数据集合都是由插件来获取的。

2.6.2 带条件的查询语句

在这里插入图片描述
在这里插入图片描述
dao层的SQL语句是 select * from student where classid = ?
拦截器的第一个处理是:根据这个SQL语句,查询总记录数 select count(*) from student where classid = ?
拦截器的第二个处理是:根据这个SQL语句,查询要显示的集合数据 select * from student where classid = limit ?, ?

从以上对比可以看出拦截器的两个操作:
第一个操作:使用 count(*) 查询记录总数
第二个操作:使用 limit ?, ? 查询要显示的数据集合

二、MyBatis配置文件中的标签

MyBatis配置文件中的标签是有顺序的,标签顺序错误,配置文件会报错。

标签 作用
properties 配置文件中的属性值
setting 修改MyBatis在运行时的行为方式
typeAliases 为java类起别名
typeHandlers 类型处理器
objectFactory 对象工厂
plugins 插件
environments 环境
mappers 映射器

1. 各标签的详细使用说明

<?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文件的内容,供当前文件使用,通过${key}来获取-->
    <properties resource="dbconfig.properties"></properties>

    <!--设置当前项目在做ResultMap映射时,做延时加载-->
    <!--lazyLoadingEnabled就是懒加载,默认值是false-->
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

    <typeAliases>
        <!--第一种方法:typeAliases为单个类起别名;type指向具体的类;alias是别名-->
        <typeAlias type="com.tentact.bean.Student" alias="Student"></typeAlias>
        <!--第二种方法:package为某个包下的类起别名,别名默认为类名-->
        <package name="com.tentact.bean"/>
    </typeAliases>

    <!--自定义的类型转换器;handler指定类型转换器类;javaType是Java数据类型;jdbcType是数据库的数据类型-->
    <typeHandlers>
        <typeHandler handler="com.common.StringArrayTypeHandler" javaType="[Ljava.lang.String;" jdbcType="VARCHAR"></typeHandler>
    </typeHandlers>

    <!--插件类-->
    <plugins>
        <!-- interceptor是拦截器;com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!--指定数据语言是mysql-->
            <property name="dialect" value="mysql"/>
            <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
            <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
            <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据,不再正常范围内 -->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>

    <!--环境;环境里可以添加多个环境变量;default来指定使用哪个环境变量-->
    <environments default="development">
        <!--environment是环境变量-->
        <environment id="development">
            <!--transactionManager是事务管理器-->
            <transactionManager type="JDBC" />
            <!--dataSource是数据源-->
            <dataSource type="POOLED">
                <!--包含的属性:驱动;数据库url;数据库用户名;数据库密码-->
                <!--这里的value是通过属性来获取的-->
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

    <!--mappers映射器,用来添加映射文件-->
    <mappers>
        <!--resource通过映射文件的路径来指定映射文件	-->
        <mapper resource="com/mapping/HealhistoryMapper.xml"></mapper>
        <mapper resource="com/mapping/PetMapper.xml"></mapper>
        <mapper resource="com/mapping/PettypeMapper.xml"></mapper>
    </mappers>
</configuration>

2. properties文件补充

2.1 properties文件位置

在JavaSE项目中properties文件直接放在src文件夹下即可。
在JavaWeb项目中properties文件需要放在resource文件夹下。

2.2 properties文件内容

properties文件存储的是键值对。在xml文件中需要通过${}来引用属性。
在xml文件中:&等符号在xml文件中需要用字符实体来代替。
在properties文件中:则直接使用&符号

举例:dbconfig.properties文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/pet?useUnicode=true&characterEncoding=utf-8
username=root
password=123456

2.3 #{}和${}的区别

  1. ${}获取的是properties文件里的值,在主配置文件里使用,是静态获取,不带引号
  2. #{}获取的是map里的值,在映射文件里使用,是动态获取,自带引号

总结

今天学习了如何使用MyBatis框架中的分页插件,相比使用之前的分页工具类而言,插件简化很多操作,使用也更加方便。还介绍了一下MyBatis配置文件中的标签,对MyBatis框架的标签也有进一步的理解。

举报

相关推荐

0 条评论