【MyBatis】简单入门 做到真正的一篇解决MyBatis

发布于:2022-11-09 ⋅ 阅读:(468) ⋅ 点赞:(0)

MyBatis入门


文章目录


在这里插入图片描述

前言

需要前置jdbc的基础 学习起来会更简单

MyBatis下载地址

在这里插入图片描述


一、MyBatis的介绍

1.1 MyBatis的历史

  • MyBatis最初是Apache的一个开源项目iBatis, 2010年6月这个项目由Apache Software Foundation迁移到了Google Code。随着开发团队转投Google Code旗下,iBatis3.x正式更名为MyBatis。代码于2013年11月迁移到Github
  • iBatis一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBatis提供的持久层框架包括SQL Maps和Data Access Objects(DAO)

1.2 MyBatis的特性

  1. MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架
  2. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
  3. MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录
  4. MyBatis 是一个 半自动的ORM(Object Relation Mapping)框架

1.3 与其它持久层技术对比

  • JDBC
  • SQL 夹杂在Java代码中耦合度高,导致硬编码内伤
    • 维护不易且实际开发需求中 SQL 有变化,频繁修改的情况多见
    • 代码冗长,开发效率低
  • Hibernate 和 JPA
  • 操作简便,开发效率高
    • 程序中的长难复杂 SQL 需要绕过框架
    • 内部自动生产的 SQL,不容易做特殊优化
    • 基于全映射的全自动框架,大量字段的 POJO 进行部分映射时比较困难。
    • 反射操作太多,导致数据库性能下降
  • MyBatis
  • 轻量级,性能出色
    • SQL 和 Java 编码分开,功能边界清晰。Java代码专注业务、SQL语句专注数据
    • 开发效率稍逊于HIbernate,但是完全能够接受

二、核心配置和组成部分

2.1 核心配置

2.1.1 mybatis配置标签的顺序

mybatis配置文件的标签遵循顺序原则,不按照顺序就会报错

properties?,settings?,typeAliases?,typeHandlers?,

objectFactory?,objectWrapperFactory?,reflectorFactory?,

plugins?,environments?,databaseIdProvider?,mappers?

2.1.2 配置标签的含义

  1. environments 配置多个连接数据库的环境
 environments
      属性  default 默认使用的环境 development 开发环境
    
environment 配置某个具体的环境
    属性 id 表示连接数据库环境的唯一标识 不能重复
    
    子标签
         transactionManager 设置事务管理方式
             属性 type="JDBC|MANAGED"
             JDBC:表示当前环境中 执行SQL,使用JDBC原生的事务管理方式 事务的提交和回滚需要手动配置
             MANAGED:被管理 例如Spring
             
         dataSource 配置数据源
            属性 type:设置数据源的类型
            type:
               POOLED:表示使用数据库连接池缓存数据库连接
               UNPOOLED:表示不适用数据库连接池
               JNDI:表示使用上下文中的数据源
  1. typeAliases 设置类型别名
    <typeAliases>
        <!--不配置alias 默认以类名为别名 不区分大小写-->
        <typeAlias type="com.worker.mb.pojo.User" alias="User"/>
        <!-- package 为包里类统一设置默认别名 为类名-->
        <package name="com.worker.mb.pojo"/>
    </typeAliases>
  1. mappers 引入映射文件

* 以包为单位引入映射文件
1. mapper接口所在的包要和映射文件所在的包一致
2. mapper接口要和映射文件一致

<!--引入映射文件-->
    <mappers>
        <!--<mapper resource="mappers/UserMapper.xml"/>-->
        <package name="com.worker.mb.mapper"/>
    </mappers>
  1. properties 引入外部资源文件
<properties resource="jdbc.properties"/>

2.2 mybatis核心配置文件

名字最好起名为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="jdbc.properties"/>

    <typeAliases>
        <!--<typeAlias type="com.worker.mb.pojo.User" alias="User"/>-->
        <package name="com.worker.mb.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--使用数据库连接词-->
            <dataSource type="POOLED">
                <property name="driver" value="${prop.driver}"/>
                <property name="url" value="${prop.url}"/>
                <property name="username" value="${prop.username}"/>
                <property name="password" value="${prop.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <!--<mapper resource="mappers/UserMapper.xml"/>-->
        <!--
        以包为单位引入映射文件
            1.mapper接口所在的包要和映射文件所在的包一致
            2.mapper接口要和映射文件一致
        -->
        <package name="com.worker.mb.mapper"/>
    </mappers>
</configuration>

2.3 引入pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.worker.mb</groupId>
    <artifactId>MyBatis-demo2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--打包方式为jar包-->
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- Mybatis核心 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.3</version>
        </dependency>

        <!-- log4j日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

2.4 组成部分

MyBatis共分为映射接口 映射文件
映射接口主要写需要进行操作的方法,比如增删改查,因为MyBatis支持面向接口编程,

只有接口没有实现类,是怎么将映射文件和映射接口产生映射关系呢?

约定:

  • java下存放java代码
  • resources存放配置文件
  • test存放测试代码
    在这里插入图片描述

三、MyBatis实现增删改查

namespace 需要写具体映射接口的全类名

  1. 映射文件内书写 select 查询 insert 插入 update 更新 delete 删除

id 为mapper接口中声明的方法名 除了查找 其余增删改都只需要写id即可
查询需要接返回类型 resultType 值为记录对应的实体类(不区分大小写)
如果返回值为Java数据类型 详情看 3.0 [MyBatis为Java的数据类型映射的别名]

  1. 映射接口只需要声明方法即可

增删改的返回值固定为受影响的行数

<mapper namespace="com.worker.mb.mappers.UserMapper"></mapper>

3.0 MyBatis为Java的数据类型映射的别名

在这里插入图片描述
在这里插入图片描述

3.1 INSERT

mapper文件

<!-- int insert(); -->
    <insert id="insert" >
        insert into user(username,password) values("张思","123456");
    </insert>

mapper接口

    /**
     * 插入
     * @return int
     */
    int insert();

3.2 DELETE

mapper文件

<!-- int delete(); -->
    <delete id="delete">
        delete from user where id = 3;
    </delete>

mapper接口

    /**
     * 插入
     * @return int
     */
    int insert();

3.3 UPDATE

mapper文件

<!-- int update(); -->
    <update id="update">
        update user set username = "章节" where id = 5;
    </update>

mapper接口

    /**
     * 删除
     * @return int
     */
    int delete();

3.4 SELECT

mapper文件

<!--
    resultType 设置默认的映射关系  ===  字段名和属性名一致
    resultMap  设置自定义的映射关系 === 字段名和属性名不一致
    -->
    <!-- User getUser -->
    <select id="getUserById" resultType="User">
        select * from user where id = 4;
    </select>

    <!-- List<User> getUsers(); -->
    <select id="getAllUser" resultType="User">
        select * from user
    </select>

mapper接口

     /**
     * 查询用户
     * @return
     */
    User getUserById();

    /**
     * 查询所有的用户信息
     */
    List<User> getAllUser();

    /**
     * 查询用户数量
     */
    int count();

四、自定义SqlSessionUtils配置类

由于每次都需要

  • 读取mybatis核心配置文件后一系列操作创建SqlSession对象
  • 统一创建工具类来创建

具体工具类代码展示:

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 java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils {

    public static SqlSession getSqlSession(){
        InputStream is = null;
        try {
            // 1. mybatis的io流方法读取mybatis核心配置文件
            is = Resources.getResourceAsStream("mybatis-config.xml");
            // 2. 创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
            // 3.使用工厂类构建对象来创建SqlSessionFactory(参数为读取配置文件的流)
            SqlSessionFactory ssf = ssfb.build(is);
            // 4. 使用SqlSessionFactory openSession方法创建SqlSession对象
            // 该对象是与数据库创建一次会话  参数为true 代表事务执行完自动提交
            SqlSession ss = ssf.openSession(true);
            return ss;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

五、MyBatis获取参数值

5.1 获取参数值的方式

MyBatis获取参数值的两种方式 ${} #{}
${} 字符串拼接 ==> 将传递的参数作为字符串拼接上去
#{} 占位符赋值 ==> 直接将参数填充到对应的占位符

5.2 获取参数值的各种情况

5.2.1 mapper方法参数为单个字面量

#{}/${} 传递的参数名任意名称都可 值才行
${} 由于是字符串拼接 需要在外围加上单引号

<!--User getUserByUsername(String username);-->
    <select id="getUserByUsername" resultType="user">
        select * from user where username = '{username}';
    </select>

5.2.2 mapper接口的方法的参数为多个时

mybatis默认会将参数存在map集合中 默认键为arg0 arg1/param1 param2 可以组合使用

<!--User checkLogin(String username,String password);-->
    <select id="checkLogin" resultType="user">
        select * from user where username = '${param1}' and password = #{arg1};
    </select>

5.2.3 自定义map集合的键 手动将参数放在Map集合

既然mybatis默认会将参数与值放进一个map集合中,代表我们也可以自定义map键值对
往map里添加的key为自定义的key,value为需要传入的值

/**
     * 验证登录
     * @param map
     * @return
     */
    User checkLoginByMap(Map<String,String> map);
<!--User checkLoginByMap(Map<String,String> map);-->
    <select id="checkLoginByMap" resultType="user">
        select * from user where username = '${username}' and password = #{password};
    </select>

》 测试方法

@Test
    public void test(){
        SqlSession ss = SqlSessionUtils.getSqlSession();
        UserMapper mapper = ss.getMapper(UserMapper.class);
       Map<String,String> map = new HashMap<>();
        map.put("username","张三");
        map.put("password","123456");
        User user = mapper.checkLoginByMap(map);
    }

5.2.4 mapper接口方法的参数是一个实体类类型的参数

此时会将从数据库查询到的字段值赋值给实体类对应的属性名

/**
     * 添加用户信息
     */
    int insertUser(User user);

当参数为实体类类型时mapper文件中的sql语句可以直接写实体类的属性名

<!--int insertUser(User user);-->
    <insert id="insertUser">
        insert into user values(null,#{username},#{password});
    </insert>

5.2.5 @Param 命名参数的键名

用注解来给键命名有两种情况
a> 以@Param的值为键 以形参为值
b> 以param1为键 以形参为值

names为存放map中的键
此时的i为0 划线中判断如果当前键没有param(i+1)则添加一个,值为传入的值
在这里插入图片描述

/**
     * @param username
     * @param passwrod
     * @return
     */
    User checkLoginByParam(@Param("username1") String username,@Param("password1") String passwrod);
<!--User checkLoginByParam(@Param("username") String username,@Param("password") String passwrod);-->
    <select id="checkLoginByParam" resultType="user">
        select * from user where username = #{username1} and password = #{password1};
    </select>

六、MyBatis的各种查询功能

  1. 若查询出的数据只有一条
    a> 可以通过实体类
    b> 集合接收
    c>可以通过map集合接收 {password=123456, id=5, username=章节}

  2. 若查询出的数据有多条
    a>以集合接收
    b>可以通过map类型的list集合接收
    c>可以通过@MapKey注解 每条数据转换的map集合作为值(键必须为不重复字段) 字段名为键
    注意:通过实体类对象接收 此时会抛出TooManyResultEception

6.1 查询一个实体类对象

a> 可以通过实体类
b> 集合接收
c>可以通过map集合接收 {password=123456, id=5, username=章节}

/**
 * 根据用户id查询用户信息
 * @param id
 * @return
 */
User getUserById(@Param("id") int id);
<!--User getUserById(@Param("id") int id);-->
<select id="getUserById" resultType="User">
	select * from t_user where id = #{id}
</select>

6.2 查询一个List集合

/**
 * 查询所有用户信息
 * @return
 */
List<User> getUserList();
<!--List<User> getUserList();-->
<select id="getUserList" resultType="User">
	select * from t_user
</select>

6.3 查询单个数据

/**  
 * 查询用户的总记录数  
 * @return  
 * 在MyBatis中,对于Java中常用的类型都设置了类型别名  
 * 例如:java.lang.Integer-->int|integer  
 * 例如:int-->_int|_integer  
 * 例如:Map-->map,List-->list  
 */  
int getCount();
<!--int getCount();-->
<select id="getCount" resultType="_integer">
	select count(id) from t_user
</select>

6.4 查询一条数据为map集合

/**  
 * 根据用户id查询用户信息为map集合  
 * @param id  
 * @return  
 */  
Map<String, Object> getUserToMap(@Param("id") int id);
<!--Map<String, Object> getUserToMap(@Param("id") int id);-->
<select id="getUserToMap" resultType="map">
	select * from t_user where id = #{id}
</select>
<!--结果:{password=123456, sex=男, id=1, age=23, username=admin}-->

6.5 查询多条数据为map集合

6.5.1 方法一

/**  
 * 查询所有用户信息为map集合  
 * @return  
 * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取  
 */  
List<Map<String, Object>> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->  
<select id="getAllUserToMap" resultType="map">  
	select * from t_user  
</select>
<!--
	结果:
	[{password=123456, sex=男, id=1, age=23, username=admin},
	{password=123456, sex=男, id=2, age=23, username=张三},
	{password=123456, sex=男, id=3, age=23, username=张三}]
-->

6.5.2 方法二

@MapKey(“id”) 指定一个值为map集合返回的键

/**
 * 查询所有用户信息为map集合
 * @return
 * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合
 */
@MapKey("id")
Map<String, Object> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
	select * from t_user
</select>
<!--
	结果:
	{
	1={password=123456, sex=男, id=1, age=23, username=admin},
	2={password=123456, sex=男, id=2, age=23, username=张三},
	3={password=123456, sex=男, id=3, age=23, username=张三}
	}
-->

七、特殊的SQL处理

在这里的SQL就需要使用 , 也算是 {},也算是 ,也算是{}的应用场景

7.1 模糊查询

模糊查询解决方案:

  1. ′ {} '% {username}%’
  2. concat —> concat(‘%’,#{username},‘%’)
  3. “%”#{username}“%” 使用单引号无法匹配成功 单引号的会与后面的作为一个整体
    select * from user where username like ‘%’?‘%’
/**
     * 根据用户名模糊查询
     */
    List<User> getUserByLike(@Param("username") String username);
<!--List<User> getUserByLike(@Param("username") String username);-->
    <select id="getUserByLike" resultType="user">
        select * from user where username like
        <!--'%${username}%'-->
        <!--concat('%',#{username},'%')-->
        "%"#{username}"%"
    </select>

7.2 批量删除

#{} 被单引号包裹 占位符会被解析为字符串 而不会被解析为占位符
${} 被解析为拼接字符串

  • 批量删除时候 #{} 会被解析会? ${} 字符串拼接 会直接将参数替换进去
/**
     * 根据id批量删除
     * @param ids
     * @return int
     * @date 2022/2/26 22:06
     */
    int deleteMore(@Param("ids") String ids);
<!--int deleteMore(@Param("id") String id);-->
    <delete id="deleteMore">
        delete from user where id in (${ids})
    </delete>

7.3 动态设置表名

#{} 报错 表名不能添加单引号

<!--List<User> getUserByTableName(@Param("tableName") String tableName);-->
    <select id="getUserByTableName" resultType="user">
        select * from ${tableName}
    </select>

7.4 添加功能获取自增的主键

  • 使用场景

  • t_clazz(clazz_id,clazz_name)

    • t_student(student_id,student_name,clazz_id)
    1. 添加班级信息
    2. 获取新添加的班级的id
    3. 为班级分配学生,即将某学的班级id修改为新添加的班级的id
  • 在mapper.xml中设置两个属性

  • useGeneratedKeys:设置使用自增的主键

    • keyProperty:因为增删改有统一的返回值是受影响的行数,因此只能将获取的自增的主键放在传输的参数user对象的某个属性中
/**
     * 添加用户信息
     */
    void insertUser(User user);
<!--void insertUser(User user);-->
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into user values(null,#{username},#{password})
    </insert>

》测试类 此时的id是自增的

//测试类
@Test
public void insertUser() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
	User user = new User(null, "ton", "123", 23, "男", "123@321.com");
	mapper.insertUser(user);
	System.out.println(user);
	//输出:user{id=10, username='ton', password='123', age=23, sex='男', email='123@321.com'},自增主键存放到了user的id属性中
}

八、自定义映射resultMap

  • resultMap:设置自定义映射
  • 属性:
    • id:表示自定义映射的唯一标识,不能重复
    • type:查询的数据要映射的实体类的类型
    • 子标签:
    • id:设置主键的映射关系
      • result:设置普通字段的映射关系
      • 子标签属性:
      • property:设置映射关系中实体类中的属性名
        • column:设置映射关系中表中的字段名
  • 若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射,即使字段名和属性名一致的属性也要映射,也就是全部属性都要列出来
<resultMap id="empResultMap" type="Emp">
	<id property="eid" column="eid"></id>
	<result property="empName" column="emp_name"></result>
	<result property="age" column="age"></result>
	<result property="sex" column="sex"></result>
	<result property="email" column="email"></result>
</resultMap>
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultMap="empResultMap">
	select * from t_emp
</select>

8.1 解决字段名与属性名的映射

字段名和属性名不一致 赋不了值 就会被赋为null

8.1.1 给表起别名

保持和属性名一致
》因为表的字段是不唯一的 查询过程中起了别名 字段名就会被修改为别名

<select id="getAllEmp" resultType="emp">
        select eid,
        emp_name as empName, <!--为下划线的字段起别名为empName -->
        age,sex,email
        from t_emp
    </select>

8.1.2 resultMap

自定义设置字段与属性的映射问题

<!-- id为resultMap的唯一标识 type为实体类类型 -->
<resultMap id="empResultMap" type="emp">
    <!--
    标签:id 设置主键的映射 result 设置普通字段的映射
        属性:property 设置映射关系的属性名 column 设置映射关系的字段名
    -->
    <id property="eid" column="eid"></id>
    <result property="empName" column="emp_name"/>
    <result property="age" column="age"/>
    <result property="sex" column="sex"/>
    <result property="email" column="email"/>
</resultMap>

8.1.3 全局配置

设置全局配置 将_自动映射为驼峰
mybatis-config.xml

<!--设置mybatis的全局配置-->
    <settings>
        <!--将下划线自动映射为驼峰 emp_name ===> empName-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
   </settings>

8.2 多对一映射(对象)

8.2.1 级联方式处理映射关系

》resultMap property=“实体类属性名.属性名” column 映射对应的字段名

<resultMap id="empAndDeptResultMapOne" type="Emp">
	<id property="eid" column="eid"></id>
	<result property="empName" column="emp_name"></result>
	<result property="age" column="age"></result>
	<result property="sex" column="sex"></result>
	<result property="email" column="email"></result>
	<result property="dept.did" column="did"></result>
	<result property="dept.deptName" column="dept_name"></result>
</resultMap>
<!--Emp getEmpAndDept(@Param("eid")Integer eid);-->
<select id="getEmpAndDept" resultMap="empAndDeptResultMapOne">
	select * from t_emp left join t_dept on t_emp.eid = t_dept.did where t_emp.eid = #{eid}
</select>

8.2.2 使用association处理映射关系

  • association:处理多对一的映射关系
  • property:需要处理多对的映射关系的属性名
  • javaType:该属性的类型
  • column: 表中对应字段名
<resultMap id="empAndDeptResultMapTwo" type="Emp">
	<id property="eid" column="eid"></id>
	<result property="empName" column="emp_name"></result>
	<result property="age" column="age"></result>
	<result property="sex" column="sex"></result>
	<result property="email" column="email"></result>
	<association property="dept" javaType="Dept">
		<id property="did" column="did"></id>
		<result property="deptName" column="dept_name"></result>
	</association>
</resultMap>
<!--Emp getEmpAndDept(@Param("eid")Integer eid);-->
<select id="getEmpAndDept" resultMap="empAndDeptResultMapTwo">
	select * from t_emp left join t_dept on t_emp.eid = t_dept.did where t_emp.eid = #{eid}
</select>

8.2.3 分步查询

将查询分为每个步骤

public class Emp {  
	private Integer eid;  
	private String empName;  
	private Integer age;  
	private String sex;  
	private String email;  
	private Dept dept;
	//...构造器、get、set方法等
}

1. 查询员工信息

  • select:设置分布查询的sql的唯一标识(namespace.SQLId或mapper接口的全类名.方法名)
  • column:设置分步查询的条件
//EmpMapper里的方法
/**
 * 通过分步查询,员工及所对应的部门信息
 * 分步查询第一步:查询员工信息
 * @param  
 * @return com.atguigu.mybatis.pojo.Emp
 * @date 2022/2/27 20:17
 */
Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);
<resultMap id="empAndDeptByStepResultMap" type="Emp">
	<id property="eid" column="eid"></id>
	<result property="empName" column="emp_name"></result>
	<result property="age" column="age"></result>
	<result property="sex" column="sex"></result>
	<result property="email" column="email"></result>
	<association property="dept"
				 select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
				 column="did"></association>
</resultMap>
<!--Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);-->
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
	select * from t_emp where eid = #{eid}
</select>

2. 查询部门信息

//DeptMapper里的方法
/**
 * 通过分步查询,员工及所对应的部门信息
 * 分步查询第二步:通过did查询员工对应的部门信息
 * @param
 * @return com.atguigu.mybatis.pojo.Emp
 * @date 2022/2/27 20:23
 */
Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);
<!--此处的resultMap仅是处理字段和属性的映射关系-->
<resultMap id="EmpAndDeptByStepTwoResultMap" type="Dept">
	<id property="did" column="did"></id>
	<result property="deptName" column="dept_name"></result>
</resultMap>
<!--Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);-->
<select id="getEmpAndDeptByStepTwo" resultMap="EmpAndDeptByStepTwoResultMap">
	select * from t_dept where did = #{did}
</select>

8.3 一对多映射(集合)

public class Dept {
    private Integer did;
    private String deptName;
    private List<Emp> emps;
	//...构造器、get、set方法等
}

8.3.1 collection

  • collection:用来处理一对多的映射关系
  • ofType:表示该属性对饮的集合中存储的数据的类型
<resultMap id="DeptAndEmpResultMap" type="Dept">
	<id property="did" column="did"></id>
	<result property="deptName" column="dept_name"></result>
	<collection property="emps" ofType="Emp">
		<id property="eid" column="eid"></id>
		<result property="empName" column="emp_name"></result>
		<result property="age" column="age"></result>
		<result property="sex" column="sex"></result>
		<result property="email" column="email"></result>
	</collection>
</resultMap>
<!--Dept getDeptAndEmp(@Param("did") Integer did);-->
<select id="getDeptAndEmp" resultMap="DeptAndEmpResultMap">
	select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
</select>

8.3.3 分步查询

1.分步查询

/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第一步:查询部门信息
 * @param did 
 * @return com.atguigu.mybatis.pojo.Dept
 * @date 2022/2/27 22:04
 */
Dept getDeptAndEmpByStepOne(@Param("did") Integer did);
<resultMap id="DeptAndEmpByStepOneResultMap" type="Dept">
	<id property="did" column="did"></id>
	<result property="deptName" column="dept_name"></result>
	<collection property="emps"
				select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
				column="did"></collection>
</resultMap>
<!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepOne" resultMap="DeptAndEmpByStepOneResultMap">
	select * from t_dept where did = #{did}
</select>

2. 根据部门id查询部门中的所有员工

/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第二步:根据部门id查询部门中的所有员工
 * @param did
 * @return java.util.List<com.atguigu.mybatis.pojo.Emp>
 * @date 2022/2/27 22:10
 */
List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第二步:根据部门id查询部门中的所有员工
 * @param did
 * @return java.util.List<com.atguigu.mybatis.pojo.Emp>
 * @date 2022/2/27 22:10
 */
List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);

8.4 延迟加载

  • 分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:
  • lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
    • aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载
  • 此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和collection中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType=“lazy(延迟加载)|eager(立即加载)”

》 mybatis-config.xml

<settings>
	<!--开启延迟加载-->
	<setting name="lazyLoadingEnabled" value="true"/>
</settings>
@Test
public void getEmpAndDeptByStepOne() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
	Emp emp = mapper.getEmpAndDeptByStepOne(1);
	System.out.println(emp.getEmpName());
}

》 mapper文件
fetchType=“lazy|eager” 开启全局延迟加载后 控制分布查询的懒加载和立即加载

<resultMap id="empAndDeptByStepResultMap" type="Emp">
	<id property="eid" column="eid"></id>
	<result property="empName" column="emp_name"></result>
	<result property="age" column="age"></result>
	<result property="sex" column="sex"></result>
	<result property="email" column="email"></result>
	<association property="dept"
				 select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
				 column="did"
				 fetchType="lazy"></association>
</resultMap>

关闭延迟加载效果 SQL语句都执行了
在这里插入图片描述
开启延迟加载效果 根据执行的方法 调用对应的SQL语句
在这里插入图片描述

九、动态SQL

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题

9.1 if

  • if标签可通过test属性(即传递过来的数据)的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行
  • 在where后面添加一个恒成立条件1=1
  • 这个恒成立条件并不会影响查询的结果
    • 这个1=1可以用来拼接and语句,例如:当empName为null时
    • 如果不加上恒成立条件,则SQL语句为select * from t_emp where and age = ? and sex = ? and email = ?,此时where会与and连用,SQL语句会报错
      • 如果加上一个恒成立条件,则SQL语句为select * from t_emp where 1= 1 and age = ? and sex = ? and email = ?,此时不报错
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp where 1=1
	<if test="empName != null and empName !=''">
		and emp_name = #{empName}
	</if>
	<if test="age != null and age !=''">
		and age = #{age}
	</if>
	<if test="sex != null and sex !=''">
		and sex = #{sex}
	</if>
	<if test="email != null and email !=''">
		and email = #{email}
	</if>
</select>

9.2 where

  • where和if一般结合使用:
  • 若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
    • 若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and/or去掉
    • 后面的and和or
   <!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
   select * from t_emp
   <where>
   	<if test="empName != null and empName !=''">
   		emp_name = #{empName}
   	</if>
   	<if test="age != null and age !=''">
   		and age = #{age}
   	</if>
   	<if test="sex != null and sex !=''">
   		and sex = #{sex}
   	</if>
   	<if test="email != null and email !=''">
   		and email = #{email}
   	</if>
   </where>
</select>

9.3 trim

  • trim用于去掉或添加标签中的内容
  • 常用属性
  • prefix:在trim标签中的内容的前面添加某些内容
    • suffix:在trim标签中的内容的后面添加某些内容
    • prefixOverrides:在trim标签中的内容的前面去掉某些内容
    • suffixOverrides:在trim标签中的内容的后面去掉某些内容
  • 若trim中的标签都不满足条件,则trim标签没有任何效果,也就是只剩下select * from t_emp
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp
	<trim prefix="where" suffixOverrides="and|or">
		<if test="empName != null and empName !=''">
			emp_name = #{empName} and
		</if>
		<if test="age != null and age !=''">
			age = #{age} and
		</if>
		<if test="sex != null and sex !=''">
			sex = #{sex} or
		</if>
		<if test="email != null and email !=''">
			email = #{email}
		</if>
	</trim>
</select>

》 测试类

//测试类
@Test
public void getEmpByCondition() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	Emp emp = new Emp(null, "张三", null, null, null, null);
	List<Emp> emps= mapper.getEmpByCondition(emp);
	System.out.println(emps);
}

9.4 choose、when、otherwise

  • choose、when、otherwise相当于if...else if..else 只会执行其中一个
  • when至少要有一个,otherwise至多只有一个
<!--List<Emp> getEmpByChoose(Emp emp);-->
    <select id="getEmpByChoose" resultType="Emp">
        select
        <include refid="empColumns"/>
        from t_emp
        <where>
            <choose>
                <when test="empName != null and empName != ''">
                    emp_name = #{empName}
                </when>
                <when test="age != null and age != ''">
                    age = #{age} and
                </when>
                <when test="sex != null and sex != ''">
                    sex = #{sex} or
                </when>
                <when test="email != null and email != ''">
                    email = #{email}
                </when>
                <otherwise>
                    did = 101
                </otherwise>
            </choose>
        </where>
    </select>

9.5 foreach

  • 属性:
  • collection:设置要循环的数组或集合
    • item:表示集合或数组中的每一个数据
    • separator:设置循环体之间的分隔符,分隔符前后默认有一个空格,如 ,
    • open:设置foreach标签中的内容的开始符
    • close:设置foreach标签中的内容的结束符

批量删除

<!--int deleteMoreByArray(@Param("eids") Integer[] eids);-->
    <delete id="deleteMoreByArray">
        delete from t_emp where
        <foreach collection="eids"  item="eid" separator="or">
            eid = #{eid}
        </foreach>
        <!--delete from t_emp where eid in
        <foreach collection="eids" item="eid" open="(" close=")" separator=",">
            #{eid}
        </foreach>-->
    </delete>

批量添加
添加的值必须来自一个item 需要加上前缀emp

<!--int insertMoreByList(List<Emp> emps);-->
    <insert id="insertMoreByList">
        insert into t_emp values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
        </foreach>
    </insert>

9.6 SQL片段

记录一段公共的sql片段 在需要使用的地方include标签进行引用
声明sql片段:<sql>标签

<!--sql片段 经常查询的部分 使用sql片段存储-->
    <sql id="empColumns">
        eid,emp_name,age,sex,email
    </sql>

引用 refid值为sql的id

<include refid="empColumns"/>

十、 MyBatis的缓存

10.1 MyBatis的一级缓存

  • 一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问
  • 使一级缓存失效的四种情况:
  1. 不同的SqlSession对应不同的一级缓存
  2. 同一个SqlSession但是查询条件不同
  3. 同一个SqlSession两次查询期间执行了任何一次增删改操作
    执行了增删改都会修改表中的数据 缓存只是为了提高查询的效率
  4. 同一个SqlSession两次查询期间手动清空了缓存

10.2 MyBatis的二级缓存

  • 二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
  • 二级缓存开启的条件
  1. 在核心配置文件中,设置全局配置属性cacheEnabled=“true”,默认为true,不需要设置
  2. 在映射文件中设置标签
  3. 二级缓存必须在SqlSession关闭或提交之后有效
  4. 查询的数据所转换的实体类类型必须实现序列化的接口

注意:

  • 使二级缓存失效的情况:两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效

10.3 二级缓存的相关配置

  • 在mapper配置文件中添加的cache标签可以设置一些属性
  • eviction属性:缓存回收策略
  • LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
    • FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
    • SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
    • WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
    • 默认的是 LRU
  • flushInterval属性:刷新间隔,单位毫秒
  • 默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句(增删改)时刷新
  • size属性:引用数目,正整数
  • 代表缓存最多可以存储多少个对象,太大容易导致内存溢出
  • readOnly属性:只读,true/false
  • true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。
    • false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false

10.4 MyBatis缓存查询的顺序

从大的查 大的查到了就不会去查小的

  • 先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用
  • 如果二级缓存没有命中,再查询一级缓存
  • 如果一级缓存也没有命中,则查询数据库
  • SqlSession关闭之后,一级缓存中的数据会写入二级缓存

10.5 整合第三方缓存EHCache(了解)

  • 添加依赖 pom.xml
<!-- Mybatis EHCache整合包 -->
<dependency>
	<groupId>org.mybatis.caches</groupId>
	<artifactId>mybatis-ehcache</artifactId>
	<version>1.2.1</version>
</dependency>
<!-- slf4j日志门面的一个具体实现 -->
<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-classic</artifactId>
	<version>1.2.3</version>
</dependency>

各个jar包的功能

jar包名称 作用
mybatis-ehcache Mybatis和EHCache的整合包
ehcache EHCache核心包
slf4j-api SLF4J日志门面包
logback-classic 支持SLF4J门面接口的一个具体实现
  • 创建EHCache的配置文件ehcache.xml(名字保持一致)
<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!-- 磁盘保存路径 -->
    <diskStore path="D:\atguigu\ehcache"/>
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>
  • 设置二级缓存的类型 === 在对应的mapper文件中设置二级缓存类型
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  • 加入logback日志
    存在SLF4J时,作为简易日志的log4j将失效,此时我们需要借助SLF4J的具体实现logback来打印日志。创建logback的配置文件logback.xml,名字固定,不可改变
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!-- 指定日志输出的位置 -->
    <appender name="STDOUT"
              class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- 日志输出的格式 -->
            <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
            <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
        </encoder>
    </appender>
    <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
    <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
    <root level="DEBUG">
        <!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
        <appender-ref ref="STDOUT" />
    </root>
    <!-- 根据特殊需求指定局部日志级别 -->
    <logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
</configuration>
  • EHCache配置文件说明
属性名 是否必须 作用
maxElementsInMemory 在内存中缓存的element的最大数目
maxElementsOnDisk 在磁盘上缓存的element的最大数目,若是0表示无穷大
eternal 设定缓存的elements是否永远不过期。 如果为true,则缓存的数据始终有效, 如果为false那么还要根据timeToIdleSeconds、timeToLiveSeconds判断
overflowToDisk 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
timeToIdleSeconds 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时, 这些数据便会删除,默认值是0,也就是可闲置时间无穷大
timeToLiveSeconds 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
diskSpoolBufferSizeMB DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
diskPersistent 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false
diskExpiryThreadIntervalSeconds 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s, 相应的线程会进行一次EhCache中数据的清理工作
memoryStoreEvictionPolicy 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。 默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出

十一、MyBatis的逆向工程

  • 正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate是支持正向工程的
  • 逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:
  • Java实体类
    • Mapper接口
    • Mapper映射文件

11.1 创建逆向工程的步骤

11.1.1 添加依赖和插件 pom.xml

<dependencies>
	<!-- MyBatis核心依赖包 -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.5.9</version>
	</dependency>
	<!-- junit测试 -->
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.13.2</version>
		<scope>test</scope>
	</dependency>
	<!-- MySQL驱动 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>8.0.27</version>
	</dependency>
	<!-- log4j日志 -->
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</version>
	</dependency>
</dependencies>
<!-- 控制Maven在构建过程中相关配置 -->
<build>
	<!-- 构建过程中用到的插件 -->
	<plugins>
		<!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
		<plugin>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-maven-plugin</artifactId>
			<version>1.3.0</version>
			<!-- 插件的依赖 -->
			<dependencies>
				<!-- 逆向工程的核心依赖 -->
				<dependency>
					<groupId>org.mybatis.generator</groupId>
					<artifactId>mybatis-generator-core</artifactId>
					<version>1.3.2</version>
				</dependency>
				<!-- 数据库连接池 -->
				<dependency>
					<groupId>com.mchange</groupId>
					<artifactId>c3p0</artifactId>
					<version>0.9.2</version>
				</dependency>
				<!-- MySQL驱动 -->
				<dependency>
					<groupId>mysql</groupId>
					<artifactId>mysql-connector-java</artifactId>
					<version>8.0.27</version>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</build>

11.1.2 创建MyBatis的核心配置文件

请看上文 有对应的配置 就不赘述了
当然其实跟mybatis逆向工程其实没啥关联,只是mybatis工程需要

11.1.3 创建逆向工程的配置文件

  • 文件名必须是:generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--
    targetRuntime: 执行生成的逆向工程的版本
    MyBatis3Simple: 生成基本的CRUD(清新简洁版)
    MyBatis3: 生成带条件的CRUD(奢华尊享版)
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3Simple">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- javaBean的生成策略-->
        <javaModelGenerator targetPackage="com.atguigu.mybatis.pojo" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <sqlMapGenerator targetPackage="com.atguigu.mybatis.mapper"
                         targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.atguigu.mybatis.mapper" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 逆向分析的表 -->
        <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
        <!-- domainObjectName属性指定生成出来的实体类的类名 -->
        <table tableName="t_emp" domainObjectName="Emp"/>
        <table tableName="t_dept" domainObjectName="Dept"/>
    </context>
</generatorConfiguration>
  • 执行MBG插件的generate目标
    在这里插入图片描述
  • 如果出现下图的错误 需要检查maven配置文件
    在这里插入图片描述
    》配上我出现的问题
    请添加图片描述

11.1.4 配张逆向生成的结构

在这里插入图片描述

11.2 按条件查询(QBC)

查询

  • selectByExample:按条件查询,需要传入一个example对象或者null;如果传入一个null,则表示没有条件,也就是查询所有数据
  • example.createCriteria().xxx:创建条件对象,通过andXXX方法为SQL添加查询添加,每个条件之间是and关系
  • example.or().xxx:将之前添加的条件通过or拼接其他条件
@Test public void testMBG() throws IOException {
	InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
	SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
	SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
	SqlSession sqlSession = sqlSessionFactory.openSession(true);
	EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
	EmpExample example = new EmpExample();
	//名字为张三,且年龄大于等于20
	example.createCriteria().andEmpNameEqualTo("张三").andAgeGreaterThanOrEqualTo(20);
	//或者did不为空
	example.or().andDidIsNotNull();
	List<Emp> emps = mapper.selectByExample(example);
	emps.forEach(System.out::println);
}

增改

  • updateByPrimaryKey:通过主键进行数据修改,如果某一个值为null,也会将对应的字段改为null
mapper.updateByPrimaryKey(new Emp(1,"admin",22,null,"456@qq.com",3));
  • updateByPrimaryKeySelective():通过主键进行选择性数据修改,如果某个值为null,则不修改这个字段
apper.updateByPrimaryKeySelective(new Emp(2,"admin2",22,null,"456@qq.com",3));`

十二、分页插件

12.1 分页插件使用步骤

12.1.1 添加依赖 pom.xml

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper</artifactId>
	<version>5.2.0</version>
</dependency>

配置分页插件

在MyBatis的核心配置文件(mybatis-config.xml)中配置插件

 <plugins>
        <!--设置分页插件-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

12.2 分页插件的使用

  • 在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能
  • pageNum:当前页的页码
    • pageSize:每页显示的条数
@Test
public void testPageHelper() throws IOException {
	InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
	SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
	SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
	SqlSession sqlSession = sqlSessionFactory.openSession(true);
	EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
	//访问第一页,每页四条数据
	PageHelper.startPage(1,4);
	List<Emp> emps = mapper.selectByExample(null);
	emps.forEach(System.out::println);
}

12.2.1 分页相关数据

计算公式 === 当前索引

index = (pageNum - 1) * pageSize

方法一:直接输出

直接打印输出Page对象

@Test
public void testPageHelper() throws IOException {
	InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
	SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
	SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
	SqlSession sqlSession = sqlSessionFactory.openSession(true);
	EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
	//访问第一页,每页四条数据
	Page<Emp> page = PageHelper.startPage(1, 4);
	List<Emp> emps = mapper.selectByExample(null);
	//在查询到List集合后,打印分页数据
	System.out.println(page);
}
  • 分页相关数据:
Page{count=true, pageNum=1, pageSize=4, startRow=0, endRow=4, total=8, pages=2, reasonable=false, pageSizeZero=false}[Emp{eid=1, empName='admin', age=22, sex='男', email='456@qq.com', did=3}, Emp{eid=2, empName='admin2', age=22, sex='男', email='456@qq.com', did=3}, Emp{eid=3, empName='王五', age=12, sex='女', email='123@qq.com', did=3}, Emp{eid=4, empName='赵六', age=32, sex='男', email='123@qq.com', did=1}]

方法二使用PageInfo

  • 在查询获取list集合之后,使用PageInfo<T> pageInfo = new PageInfo<>(List<T> list, intnavigatePages)获取分页相关数据
  • list:分页之后的数据
    • navigatePages:导航分页的页码数
@Test
public void testPageHelper() throws IOException {
	InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
	SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
	SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
	SqlSession sqlSession = sqlSessionFactory.openSession(true);
	EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
	PageHelper.startPage(1, 4);
	List<Emp> emps = mapper.selectByExample(null);
	PageInfo<Emp> page = new PageInfo<>(emps,5);
	System.out.println(page);
}
  • 分页相关数据:
PageInfo{
pageNum=1, pageSize=4, size=4, startRow=1, endRow=4, total=8, pages=2, 

list=Page{count=true, pageNum=1, pageSize=4, startRow=0, endRow=4, total=8, pages=2, 
reasonable=false, pageSizeZero=false}[Emp{eid=1, empName='admin', age=22, sex='男', 
email='456@qq.com', did=3}, Emp{eid=2, empName='admin2', age=22, sex='男', email='456@qq.com', 
did=3}, Emp{eid=3, empName='王五', age=12, sex='女', email='123@qq.com', did=3}, Emp{eid=4, 
empName='赵六', age=32, sex='男', email='123@qq.com', did=1}], 

prePage=0, nextPage=2, isFirstPage=true, isLastPage=false,
hasPreviousPage=false, hasNextPage=true, 
navigatePages=5, navigateFirstPage=1, navigateLastPage=2, 
navigatepageNums=[1, 2]}
  • 其中list中的数据等同于方法一中直接输出的page数据

12.2.2 常用数据:

  • pageNum:当前页的页码
  • pageSize:每页显示的条数
  • size:当前页显示的真实条数
  • total:总记录数
  • pages:总页数
  • prePage:上一页的页码
  • nextPage:下一页的页码
  • isFirstPage/isLastPage:是否为第一页/最后一页
  • hasPreviousPage/hasNextPage:是否存在上一页/下一页
  • navigatePages:导航分页的页码数
  • navigatepageNums:导航分页的页码,[1,2,3,4,5]

总结

以上就是今天要讲的内容,本文仅仅简单介绍了

本文含有隐藏内容,请 开通VIP 后查看