• 【MyBatis】MyBatis是什么?能干什么?一篇学习MyBatis,知识点详细解释,实例演示


    文章目录

    MyBatis

    环境

    • jdk 1.8.0_261
    • mysql 8.0.22
    • maven 3.8.4
    • idea

    • JDBC
    • Mysql
    • Maven
    • Junit
    • SSM框架

    学习过程中的代码测试及数据库:
    链接:https://pan.baidu.com/s/1hJ9jTSeN6Z1xQHBRCrT_Ww?pwd=1111
    提取码:1111

    官网文档:MyBatis中文网

    1、简介

    1.1 什么是MyBatis?

    1. apache的开源项目,原名IBatis
    2. 持久层框架
    3. 几乎避免了所有的JDBC代码和手动设置参数以及获取结果集
    4. 可以使用xml或直接来配置和映射原生类型、接口和Java的POJO(Plain Old Java Objects,普通老式Java对象)为数据库中的记录
    5. 2013年迁移到github

    1.2 如何获得MyBatis?

    • GitHub源码地址:https://github.com/mybatis/mybatis-3/releases
    • 中文文档地址:MyBatis中文网
    • Maven仓库:https://mvnrepository.com/search?q=mybatis

    1.3 持久化?

    数据持久化

    • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
    • 内存:断电即丢、失
    • 数据库(jdbc),io文件持久化
    • 生活中例子:冷藏,罐头。
    • 为什么需要持久化?
      • 有一些对象不能让他丢失。
      • 内存太贵了

    1.4 持久层?

    Dao层,Servce层,Controller层…

    • 完成持久化工作的代码块
    • 界限十分明显

    1.5 为什么需要Mybatis?

    • 帮助程序员将数据存入到数据库中

    • 方便

    • 传统的JDBC代码太复杂了,简化,自动化

    • 不用MyBatis也可以,更容易上手

    • 优点:

      • 简单简单,小
      • 灵活
      • sql和代码分离,提高了可维护性
      • 提供映射标签,支持对戏那个和数据库的orm字段关系映射
      • 提供对象映射标签,支持对象关系组件卫华
      • 提供xml标签,支持编写动态sql
      • 使用的人多!
        • Spring SpringMVC SpringBoot 使用的人多

    2、第一个MyBatis程序

    思路:搭建环境–> 导入MyBatis–>编写代码–>测试!

    2.1 搭建环境

    1 搭建数据库

    # MyBatis案例
    
    # 创建数据库
    CREATE DATABASE mybatis
    
    USE mybatis
    
    CREATE TABLE `user`(
    	`id` INT NOT NULL PRIMARY KEY,
    	`name` VARCHAR(30) DEFAULT NULL,
    	`pwd` VARCHAR(30) DEFAULT NULL
    )ENGINE=INNODB DEFAULT CHARSET=utf8;  
    # engine=innodb 设置引擎,innodb支持事务
    
    DROP TABLE `user`
    
    INSERT INTO `user` (`id`, `name`, `pwd`)
    VALUES
      ('1', '狂神', '123'),
      ('2', '张三', '123'),
      ('3', '李四', '123')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    2 新建项目

    1. 新建一个普通Maven项目

      1. new project -->maven(com.kuang / MyBatis-Study)–> finish

        创建成功后,看一下maven配置

        image-20220721101945747

    2. 删除src文件,将项目作为父工程

    3. 导入依赖

      pom.xml

      
      <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.0modelVersion>
      
          
          <groupId>com.kuanggroupId>
          <artifactId>MyBatis-StudyartifactId>
          <version>1.0-SNAPSHOTversion>
      
          
          <dependencies>
              
              <dependency>
                  <groupId>mysqlgroupId>
                  <artifactId>mysql-connector-javaartifactId>
                  <version>8.0.16version>
              dependency>
              
              <dependency>
                  <groupId>org.mybatisgroupId>
                  <artifactId>mybatisartifactId>
                  <version>3.4.2version>
              dependency>
              
              <dependency>
                  <groupId>junitgroupId>
                  <artifactId>junitartifactId>
                  <version>4.11version>
                  <scope>testscope>
              dependency>
          dependencies>
      
      
      
      project>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37

    2.2 创建一个模块

    1 写入mybatis-config.xml配置文件

    • 在resources中写入mybatis-config.xml配置文件;

      新建子模块项目 new model --> mybatis-01 --> finish

      image-20220721135628659

      mybatis-config.xml

      模板参考:https://mybatis.org/mybatis-3/zh/getting-started.html

      
      DOCTYPE configuration
              PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-config.dtd">
      
      <configuration>
          
          <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://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
                      <property name="username" value="root"/>
                      <property name="password" value="root"/>
                  dataSource>
              environment>
          environments>
      
      configuration>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22

    2 编写MyBatisUtils类

    • 编写一个mybatis工具类

      目的,生成SqlSession实例

      image-20220721140026162

      MybatisUtil.java

      package com.kuang.utils;
      
      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 javax.annotation.Resource;
      import java.io.InputStream;
      
      //sqlSessionFactory --> sqlSession
      public class MyBatisUtils {
      
          private static SqlSessionFactory sqlSessionFactory;
      
          //一初始化就加载
          static {
              try {
                  //使用mybatis第一步:获取SqlSessionFactory实例
                  String resource = "mybatis-config.xml";
                  InputStream inputStream = Resources.getResourceAsStream(resource);
                  sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
              }catch (Exception e){
                  e.printStackTrace();
                  System.out.println("SqlSessionFactory实例获取异常");
              }
          }
      
          //第二步:有了SqlSessionFactory,我们就可以从中获得SqlSession实例
          //SqlSession完全包含面向数据库执行SQL命令所需要的方法
          public static SqlSession getSqlSession(){
              return sqlSessionFactory.openSession();
          }
      
      
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36

    2.3 编写代码

    之前步骤:

    1. 写实体类 pojo包 : 简单的 Java 对象(Plain Ordinary Java Object)
    2. 写Dao接口 dao包
    3. 写接口实现类 类daoimpl.java

    MyBatis步骤:

    1. 写实体类
    2. 写Dao接口
    3. 写接口实现类 类Mapper.xml or 通过注解方式来实现接口类

    第三点发生了变化: 这样几乎避免了所有的JDBC代码和手动设置参数以及获取结果集

    1 写实体类

    User.java

    package com.kuang.pojo;
    
    public class User {
    
        private int id;
        private String name;
        private String pwd;
    
        //无参构造
        public User() {
        }
    
        //有参构造
        public User(int id, String name, String pwd) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
        }
    
        //get & set
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    2 写类dao接口

    UserDao.java (interface)

    package com.kuang.dao;
    
    import com.kuang.pojo.User;
    
    import java.util.List;
    
    public interface UserDao {
    
        List<User> getUserList();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3 写接口实现类

    • 接口实现类由原来的UserDaoImpl转换为现在的Mapper配置文件

    (原来)写dao层接口实现类impl

    image-20220721143103904

    UserDaoImpl.java

    package com.kuang.dao;
    
    import com.kuang.pojo.User;
    
    import java.util.List;
    
    public class UserDaoImpl implements UserDao{
        public List<User> getUserList(){
            
            //执行sql语句
            String sql = "select * from mybatis.user"
            //获取结果集   ResultSet
          	 ...
                
            return null;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    (mybatis)写dao层接口的Mapper.xml

    UserDaoMapper.xml

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    
    <mapper namespace="com.kuang.dao.UserDao">
        
        <select id="getUserList" resultType="com.kuang.pojo.User">
            select * from mybatis.user
        select>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.4 测试

    测试包与项目包一一对应;

    1 测试dao

    image-20220723144111437

    image-20220723154332711

    UserDaoTest.java

    package com.kuang.utils;
    
    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 javax.annotation.Resource;
    import java.io.InputStream;
    
    //创建SqlSession的工具类(就是个工具人),这个工具人做了一件事,把mybatis-config.xml资源加载进来,创建一个sqlSession对象
    //sqlSessionFactory --> sqlSession
    public class MyBatisUtils{
    
        private static SqlSessionFactory sqlSessionFactory;
    
        //一初始化就加载
        static {
            try {
                //使用mybatis第一步:获取SqlSessionFactory实例
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("SqlSessionFactory实例获取异常");
            }
        }
    
        //第二步:有了SqlSessionFactory,我们就可以从中获得SqlSession实例
        //SqlSession完全包含面向数据库执行SQL命令所需要的方法
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    点击运行:

    测试结果:查询出了user表中所有信息

    image-20220725132429330

    问题1:找不到mybaits-config.xml文件

    未扫描到MyBatis-config.xml文件

    解决办法:加个过滤器,让xml文件能被扫描到

    在pom.xml中加入资源过滤

        
        <build>
            <resources>
                <resource>
                    <directory>src/main/resourcesdirectory>
                    <includes>
                        <include>**/*.propertiesinclude>
                        <include>**/*.xmlinclude>
                    includes>
                    <filtering>truefiltering>
                resource>
                <resource>
                    <directory>src/main/javadirectory>
                    <includes>
                        <include>**/*.propertiesinclude>
                        <include>**/*.xmlinclude>
                    includes>
                    <filtering>truefiltering>
                resource>
            resources>
        build>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    客官移步这里

    【问题解决】Cause: java.io.IOException: Could not find resource com/kuang/dao/UserMapper.xml_宋丹敏的博客-CSDN博客

    问题2:Mapper未注册

    解决办法:去mybatis-config.xml文件中注册一下:

    在mybtis-config.xml中加入:

        <mappers>
            <mapper resource="com/kuang/dao/UserMapper.xml">mapper>
        mappers>
    
    • 1
    • 2
    • 3

    客官移步这里

    【问题解决】Cause: java.io.IOException: Could not find resource com/kuang/dao/UserMapper.xml_宋丹敏的博客-CSDN博客

    问题3: UTF-8改为UTF8

    客官移步这里

    【问题解决】org.apache.ibatis.exceptions.PersistenceException: Error building SqlSession.1 字节的 UTF-8 序列的字_宋丹敏的博客-CSDN博客

    问题4:url未加时区问题

    客官移步这里

    【问题解决】Cause: java.sql.SQLException: The server time zone value ‘�й���׼ʱ��‘ is unrecognized or repres_宋丹敏的博客-CSDN博客

    可能遇到的问题汇总:

    1. 配置文件没有注册
    2. 绑定接口错误
    3. 方法名不对
    4. 返回类型不对
    5. Maven资源导出问题

    3、CRUD增删改查

    Create Read Update delete

    1. namespace

    namespace中的包名要和Dao/Mapper接口的包名一致!

    <mapper namespace="com.kuang.dao.UserMapper">   
       
    mapper>
    
    • 1
    • 2
    • 3

    案例:

    通过id查询一个用户的信息;

    1. 编写接口 UserMapper.java ==== UserDao.java

      UserMapper.java

      //查询一条信息
      User getUserById(int id);
      
      • 1
      • 2
    2. 编写对应的mapper中的sql语句

      UserMapper.xml

      <select id="getUserById" resultType="com.kuang.pojo.User">
          select * from mybatis.user where id=#{id}
      select>
      
      • 1
      • 2
      • 3
    3. Junit测试:

      UserMapperTest.java

      @Test
      public void getUserById(){
          //获取SqlSession(固定的)
          SqlSession sqlSession = MyBatisUtils.getSqlSession();
      
          //拿到测试的接口
          UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
          //给接口参数id一个的具体数值
          User user = userMapper.getUserById(1);
          //显示查询回来的数据
          System.out.println(user);
      
          //关闭SqlSession(固定的)
          sqlSession.close();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15

    2. select

    选择,查询语句;

    • id 就是对应的namespece中的方法名
    • resultType sql语句执行的返回值
    • parameterType 参数类型

    UserMapper.java

    //查询所有信息
    List<User> getUserList();
    
    //查询一条信息
    User getUserById(int id);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    UserMapper.xml

    
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    select>
    <select id="getUserById" resultType="com.kuang.pojo.User">
        select * from mybatis.user where id=#{id}
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3. add

    UserMapper.java

    //插入一个用户信息
    int addUser(User user);
    
    • 1
    • 2

    UserMapper.xml

    
    <insert id="addUser" parameterType="com.kuang.pojo.User" >
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
    insert>
    
    • 1
    • 2
    • 3
    • 4

    4. update

    UserMapper.java

    //修改用户
    int updateUser(User user);
    
    
    • 1
    • 2
    • 3

    UserMapper.xml

    
    <update id="updateUser" parameterType="com.kuang.pojo.User" >
        UPDATE mybatis.user SET NAME=#{name},pwd=#{pwd} WHERE id=#{id}
    update>
    
    • 1
    • 2
    • 3
    • 4

    5. delete

    UserMapper.java

    //删除用户
    int deleteUser(int id);
    
    • 1
    • 2

    UserMapper.xml

    
    <delete id="deleteUser" parameterType="int">
        DELETE FROM mybatis.user WHERE id = #{id}
    delete>
    
    • 1
    • 2
    • 3
    • 4

    注意:

    增删改都需要提交事物,查询不需要提交事物

    CRUD总结:

    UserMapper.java

    package com.kuang.dao;
    
    import com.kuang.pojo.User;
    
    import java.util.List;
    
    public interface  UserMapper{
    
        /*
           知识补充:
            泛型:E,就是一种不确定的数据类型
            默认泛型类型:Object类型   ArrayList
            确定了泛型的集合:  ArrayList list = new ArrayList<>();
            没有确定泛型的集合:ArrayList list = new ArrayList();
    
         */
    
        //查询所有信息
        List<User> getUserList();
    
        //查询一条信息
        User getUserById(int id);
    
        //插入一个用户信息
        int addUser(User user);
    
        //修改用户
        int updateUser(User user);
    
        //删除用户
        int deleteUser(int id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    UserMapper.xml

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    
    <mapper namespace="com.kuang.dao.UserMapper">
        
        <insert id="addUser" parameterType="com.kuang.pojo.User" >
            insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
        insert>
    
        
        <update id="updateUser" parameterType="com.kuang.pojo.User" >
            UPDATE mybatis.user SET NAME=#{name},pwd=#{pwd} WHERE id=#{id}
        update>
    
        
        <delete id="deleteUser" parameterType="int">
            DELETE FROM mybatis.user WHERE id = #{id}
        delete>
    
        
        <select id="getUserList" resultType="com.kuang.pojo.User">
            select * from mybatis.user
        select>
        <select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
            select * from mybatis.user where id=#{id}
        select>
    
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    UserMapperTest.java

    package com.kuang.dao;
    
    
    import com.kuang.pojo.User;
    import com.kuang.utils.MyBatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    /*
        测试UserMapper
    
            UserMapper是接口,是实现这个接口的配置文件
            所以需要测试从后端拿到的数据是否想要的,只需要测试接口就行
    
            如何测试接口?
                第一步:先获取SqlSession对象
                        之前在MyBatisUtils中已经生成了SqlSession  (SqlSessionFactoryBuilder-->SqlSessionFactoru-->SqlSession)
                        所以现在直接从MyBatisUtils中获取SqlSession
                        获取到SqlSession对象后来执行sql操作
                第二步:执行sql
                       通过SqlSession.getMapper()来获取Mapper,getMapper()方法中的参数,就是UserMapper实例
                       如何获取UserMapper实例?
                            方式一 通过拿到UserMapper.class来获取UserMapper对象的实例
                            方式二 通过获取对象流来获取对象实例
                第三步:遍历出数组的数据
                第四步:关闭SqlSession
    
            拿到UserMapper接口对象的实例,就是拿到了从数据库查询到的数据,最终就可以达到测试的目的
     */
    public class  UserMapperTest{
    
        @Test
        public void test(){
    
            //获取SqlSession
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
    
            try {
                //执行sql
                //方式一 getMapper
                UserMapper UserMapper = sqlSession.getMapper(UserMapper.class);
                List<User> userList = UserMapper.getUserList(); //拿到查询到的所有用户信息
    
                //方式二 selectList
                List<User> userList1 = sqlSession.selectList("com.kuang.dao.UserMapper.getUserList");
                //遍历出数组中的数据  增强for循环  userList.for自动生成
                for (User user : userList) {
                    System.out.println(user);
                }
    
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("test异常");
            }finally {
                //关闭SqlSession
                sqlSession.close();
            }
        }
    
        @Test
        public void getUserById(){
            //获取SqlSession(固定的)
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
    
            //拿到测试的接口
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //给接口参数id一个的具体数值
            User user = userMapper.getUserById(1);
            //显示查询回来的数据
            System.out.println(user);
    
            //关闭SqlSession(固定的)
            sqlSession.close();
        }
    
        @Test
        public void  addUser(){
             //获取sqlSession (固定)
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
    
            //拿到要测试的接口的实例
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //给接口实例传一个添加的用户的数据
            int res = userMapper.addUser(new User(5,"baby","123"));
            //输出数据库中的所有信息,查看是否插入成功
            if (res>0){
                System.out.println("插入一条user成功!");
            }
    
            //增删改需要提交事务,否则数据添加不到数据库中去 (固定)
            sqlSession.commit();
            //关闭sqlSesion (固定)
            sqlSession.close();
    
        }
    
        @Test
        public void updateUser(){
            //获取SqlSession
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
    
            //拿到要测试的updateUser接口
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //给接口实例中填入要修改的内容
            int res = userMapper.updateUser(new User(4,"dada","456"));
    
            if (res>0){
                System.out.println("修改一条信息成功");
            }
            //增删改需要提交事务,否则数据库中数据不会变化
            sqlSession.commit();
            //关闭sqlsession
            sqlSession.close();
    
        }
    
        @Test
        public void deleteUser(){
            //获取sqlsession
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
    
            //拿到要测试的接口
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //给实例一个测试删除的用户id
            int res = userMapper.deleteUser(3);
            System.out.println(res);//有删除的,返回1  没有删除的,返回0
            if (res > 0){
                System.out.println("删除一个用户成功!");
            }
    
            //增删改,需要提交事务
            sqlSession.commit();
            //关闭sqlsession
            sqlSession.close();
        }
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140

    image-20220725152330275

    6. 分析错误

    • 标签不要匹配错
    • namespace中的命名空间是UserMapper接口的名字,中间是 . 隔开
    • resources绑定mapper,需要使用路径,路径都是 / 隔开
    • 程序配置文件必须符合规范
    • 空指针异常,原因是定义的变量没有使用
    • 输出的xml文件中存在中文乱码问题
    • maven资源没有导出问题
    • mapper未注册问题
    • utf-8改为utf8问题
    • url未加时区问题

    7、万能的Map & 模糊查询拓展

    客观移步这里

    【Map】万能的Map使用方法 & 模糊查询的两种方式_宋丹敏的博客-CSDN博客

    4、配置解析

    官方中文文档:https://mybatis.org/mybatis-3/zh/configuration.html

    image-20220726101542230

    1. 核心配置文件

    • mybatis-config.xml

    • MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息

    • configuration(配置)
      properties(属性)
      settings(设置)
      typeAliases(类型别名)
      typeHandlers(类型处理器)
      objectFactory(对象工厂)
      plugins(插件)
      environments(环境配置)
      environment(环境变量)
      transactionManager(事务管理器)
      dataSource(数据源)
      databaseIdProvider(数据库厂商标识)
      mappers(映射器)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13

    mybatis-config.xml

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        
        <properties resource="db.properties">
            
            <property name="username" value="root"/>
            <property name="password" value="111"/>
        properties>
    
        
        <environments default="development">
    
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                dataSource>
            environment>
    
            
            <environment id="test">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                dataSource>
            environment>
        environments>
    
        
        <mappers>
            <mapper resource="com/kuang/dao/UserTMapper.xml">mapper>
        mappers>
    
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    2. 环境配置(environments)

    MyBatis可以配置适应多种环境

    不过,虽然可以配置多种环境,但是每个SqlSessionFactory实例只能选择一种环境。

    MyBatis默认的事务管理器是:JDBC, 连接池是: POOLED

    
    <environments default="development">
    
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            dataSource>
        environment>
    
        
        <environment id="test">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            dataSource>
        environment>
    environments>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3. 属性(properties)

    我们可以通过properties属性来实现引用配置文件

    这些属性都是可外部配置且动态替换的,既可以在典型的Java属性文件中配置,亦可以通过properties原色的子元素来传递

    编写一个配置文件:

    db.properties

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true
    root=root
    password=root
    
    • 1
    • 2
    • 3
    • 4

    mybatis-config.xml 导入db.properties文件

    
    <properties resource="db.properties">
        
        <property name="username" value="root"/>
        <property name="password" value="111"/>
    properties>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    注意:在xml文件中所有标签都可以规定其顺序

    报错:

    The content of element type “configuration” must match “(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)”.

    元素类型"configuration"的内容必须匹配"(属性?,设置?,类型别名?,类型处理程序?,objectFactory?,objectWrapperFactory?,reflectorFactory?,插件?,环境?,databaseIdProvider?,映射器?)"

    原因:

    properties标签顺序错误

    标签顺序:properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?

    解决办法:

    properites 标签在configuration 中 第一个顺序

    4. 类型别名(typeAliases)

    • 可以给实体类起别名
    • 存在的意义仅仅在于用来减少类完全限定名的冗余

    方式一

    • 直接给实体类起别名

    mybatis-config.xml

    
    <typeAliases>
        <typeAlias alias="UserT" type="com.kuang.pojo.UserT"/>
    typeAliases>
    
    • 1
    • 2
    • 3
    • 4

    UserMapper.xml

    
    <insert id="addUserT" parameterType="UserT">
        insert into user(id,name,pwd) values (#{id},#{name},#{pwd})
    insert>
    
    • 1
    • 2
    • 3
    • 4

    方式二

    • 指定一个包名

    也可以指定一个包名,MyBatis会在包名下面搜索需要的Java Bean,比如扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!

    mybaits-config.xml

    
    <typeAliases>
        <package name="com.kuang.pojo"/>
    typeAliases>
    
    • 1
    • 2
    • 3
    • 4

    UserMapper.xml

    
    <select id="getUserTList" resultType="userT">
        select * from user
    select>
    
    • 1
    • 2
    • 3
    • 4

    方式三

    注解方式

    • 将注解标签写到实体类上面

    UserT.java

    @Alias("hello")
    public class UserT {
    ...
    }
    
    • 1
    • 2
    • 3
    • 4

    UserTMapper.xml

    
    <select id="getUserTList" resultType="hello">
        select * from user
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 在实体类比较少的时候,使用第一种方式。

      如果实体类比较多,建议使用第二种。

      第一种可以DIY自定义,第二种不行,进入过非要改,在实体类上增加注解。

    5. 设置(setting)

    中文官方文档:https://mybatis.org/mybatis-3/zh/configuration.html#settings

    • 数据库–Java 开启自动驼峰命名映射

      mapUnderscoreToCameICase

    • logImpl 指定mybatis所用日志的具体实现,未指定时将自动查找

      image-20220726164532109

    • image-20220726164439330

    6. 其他配置

    • typeHandler(类处理器)

    • objectFactory(对象工厂)

    • plugins插件

      • mybatis-generator-core
      • mybatis-plus
      • 通用mapper

    7.映射器(mappers)

    MapperRegistry : 注册绑定我们的 Mapper 文件;

    方式一【推荐使用】

    mybatis-config.xml

    • 通过xml注册
    
    <mappers>
        <mapper resource="com/kuang/dao/UserTMapper.xml">mapper>
    mappers>
    
    • 1
    • 2
    • 3
    • 4

    方式二

    • 通过class类注册

    mybatis-config.xml

    
    <mappers>
        <mapper class="com.kuang.dao.UserTMapper">mapper>
    mappers>
    
    • 1
    • 2
    • 3
    • 4

    注意点:

    • 接口和它的Mapper配置文件必须同名!
    • 接口和它的Mapper配置文件必须在同一个包下!

    方式三

    • 将类所在包进行注册

    mybatis-config.xml

    
    <mappers>
        <package name="com.kuang.dao"/>
    mappers>
    
    • 1
    • 2
    • 3
    • 4

    注意点:

    • 接口和它的Mapper配置文件必须同名!
    • 接口和它的Mapper配置文件必须在同一个包下!

    8. 生命周期和作用域

    image-20220727085415679

    生命周期,和作用域,是至关重要的,因为错误的使用会导致严重的并发问题

    SqlSessionFactoryBuilder

    • 一旦创建SqlSessionFactory,就不再需要它了
    • 局部变量

    SqlSessionFactory

    • 说白了,就可以想象为数据库连接池
    • SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃或者重新创建另一个实例
    • 因此SqlSessionFactory的最佳作用域是应用作用域
    • 最简单的就是使用单例模式或者静态单例模式

    SqlSession

    • 连接到连接池的一个请求!
    • 关闭
    • 用完之后需要关闭,否则资源占用!

    image-20220727100254385

    这里的每一个mapper就是指的每个具体的业务!

    5、 ResultMap结果集映射

    解决属性名和字段名不一致的问题

    解决办法:

    1. sql语句中的属性名起别名
    2. ResultMap结果集映射
    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.kuang.dao.UserMapper">
    
        
    
        <resultMap id="user" type="User">
            
            <result property="id" column="id">result>
            <result property="name" column="name">result>
            <result property="password" column="pwd">result>
        resultMap>
        <select id="findUserById" resultMap="user">
            select id,name,pwd as password from user where id=#{id}
        select>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • ResultMap元素是MyBatis中最重要最强大的元素

    • ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂的语句,只需要描述他们的关系

          
          <result property="password" column="pwd">result>
      
      • 1
      • 2

    6、日志

    6.1 日志工厂

    如果一个数据库操作,出现了异常,我们就需要拍错,日志就是最好的助手!

    曾经:sout 、 debug

    现在:日志工厂

    https://mybatis.org/mybatis-3/zh/configuration.html#settings

    image-20220727140754384

    • SLF4J simple logging facade for java的缩写,java的简单日志外观

    • LOG4J(3.5.9 起废弃) 【掌握】

    • LOG4J2

    • JDK_LOGGING

    • COMMONS_LOGGING

    • STDOUT_LOGGING 【掌握】

    • NO_LOGGING

    在mybatis中具体使用哪个日志试下,在setting中设定!

    STDOUT_LOGGING 标准日志输出

    image-20220727151508010

    mybaits-config.xml

    <settings>
        
        
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    6.2 log4j

    什么是log4j?

    • 是apache的一个开源项目
    • 通过log4j,我们可以控制日志信息输送的目的地是控制台 or 文件内 or GUI组件
    • 可以通过log4j控制每一条日志的输出格式
    • 通过定义每一条日志信息的级别,能够更加细致的控制日志的生产过程
    • 通过一个配置文件来灵活配置,【log4j.properties 】,不需要修改代码

    如何使用log4j?

    1. 导入log4j jar包\

      pom.xml

      
      <dependency>
          <groupId>log4jgroupId>
          <artifactId>log4jartifactId>
          <version>1.2.17version>
      dependency>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    2. 在resources下建立log4j.properties

      log4j.properties

      #将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
      log4j.rootLogger=DEBUG,console,file
      
      #控制台输出的相关设置
      log4j.appender.console = org.apache.log4j.ConsoleAppender
      log4j.appender.console.Target = System.out
      log4j.appender.console.Threshold=DEBUG
      log4j.appender.console.layout = org.apache.log4j.PatternLayout
      log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
      
      #文件输出的相关设置
      log4j.appender.file = org.apache.log4j.RollingFileAppender
      log4j.appender.file.File=./log/kuang.log
      log4j.appender.file.MaxFileSize=10mb
      log4j.appender.file.Threshold=DEBUG
      log4j.appender.file.layout=org.apache.log4j.PatternLayout
      log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
      
      #日志输出级别
      log4j.logger.org.mybatis=DEBUG
      log4j.logger.java.sql=DEBUG
      log4j.logger.java.sql.Statement=DEBUG
      log4j.logger.java.sql.ResultSet=DEBUG
      log4j.logger.java.sql.PreparedStatement=DEBUG
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
    3. 配置log4j为日志的实现

      mybatis-config.xml

      <settings>
          
          <setting name="logImpl" value="LOG4J"/>
      settings>
      
      • 1
      • 2
      • 3
      • 4
    4. Log4j的使用,测试运行findUserById

      UserMapperTest.java

      package com.kuang.dao;
      
      import com.kuang.pojo.User;
      import com.kuang.utils.MyBatisUtils;
      import org.apache.ibatis.session.SqlSession;
      import org.junit.Test;
      
      public class UserMapperTest {
      
          @Test
          public void findUserByIdTest(){
      
              SqlSession sqlSession = MyBatisUtils.getSqlSession();
      
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      
              User user = userMapper.findUserById(2);
      
              System.out.println(user);
      
              sqlSession.close();
      
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24

      测试结果:

      image-20220727154932140

      自动生成了log文件:image-20220727155504289

    简单使用

    1. 要在使用log4j的类中,导入包 import org.apache.log4j.Logger;

    2. 日志对象,参数为当前类的class

      static Logger logger = Logger.getLogger(UserDaoTest.class);
      
      • 1
    3. 日志级别

      logger.info("info:进入了testLog4j方法");
      logger.error("error:进入了testLog4j方法");
      logger.debug("debug:进入了testLog4j方法");
      
      • 1
      • 2
      • 3

    UserMapperTest.java

    package com.kuang.dao;
    
    import com.kuang.pojo.User;
    import com.kuang.utils.MyBatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.log4j.Logger;
    import org.junit.Test;
    
    public class UserMapperTest {
    
    
        @Test
        public void findUserByIdTest(){
    
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
    
            //拿到UserMapper对象实例
            Logger logger = Logger.getLogger(UserMapper.class);
            logger.info("测试,进去getUserById方法成功!");
    
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.findUserById(2);
            System.out.println(user);
    
            sqlSession.close();
    
        }
    
        @Test
        public void testLog4j(){
            //拿到UserMapper对象实例
            Logger logger = Logger.getLogger(UserMapper.class);
    
            logger.info("info:进入了testLog4j方法");
            logger.error("error:进入了testLog4j方法");
            logger.debug("debug:进入了testLog4j方法");
    
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    kuang.log

    image-20220727160808405

    7、分页

    为什么要分页?

    • 要查询的数据量过大的时候,需要减少数据的处理量,提高效率

    使用Limit分页

    语法:SELECT * FROM USER LIMIT startindex,pagesize
    
    • 1
    -- 从第0个开始查,每页查3个
    SELECT * FROM USER LIMIT 0,3
    
    -- 从第0开始查,到第2个结束  limit后面只有一个参数,就相当于[0,n]
    SELECT * FROM USER LIMIT 2  
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1、mybatis实现分页

    UserMapper.java

    //findAllUserByLimit  param:startindex,pagesize
    List<User> findAllUserByLimit(HashMap<String,Object> map);
    
    • 1
    • 2

    UserMapper.xml

    <select id="findAllUserByLimit" parameterType="map" resultType="User">
        SELECT * FROM USER LIMIT #{startIndex},#{pageSize}
    select>
    
    • 1
    • 2
    • 3

    UserMapperTest.java

    /*
        分页查询
            传递两个参数: startIndex, pagesize
            传参结构: HashMap 键值对形式
    		
    	这里为什么要用HashMap?
    		说白了,这个HashMap就是用来传递多个参数的;
    		
    		传递一个参数一般使用int类型,比如通过id查询用户信息:User findUserById(int id);
    		传递两个参数可以直接传递,比如通过名字和性别来查询用户信息:User findUser(int name,String sex);
    		
    		那传递两个及两个以上呢?
    		
    		这样一个一个在这里写参数是不是很麻烦,而且可读性不强;
    		这里就可以使用HashMap来进行传递,
    		比如通过名字和性别来查询用户信息,就可以这样写:List findUser(HashMap map);
    		这里传参就直接是map,这样测试的时候,就直接通过map.put(key,value),将多个要传递的参数的值放入map中,从而传递到后端;
    		如果还没明白,看下面这个例子
    		
     */
    @Test
    public void testfindAllUserLimit(){
    
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    
        int currentPage = 1; // 第几页
        int pageSize = 3; //每页显示几个
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("startIndex", (currentPage-1)*pageSize);
        map.put("pageSize", pageSize);
    
        List<User> userList = userMapper.findAllUserByLimit(map);
        for (User user : userList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    2、RowBounds对象实现分页【不推荐】

    UserMapper.java

    //分页2
    //通过RowBounds类实现【不推荐】
    List<User> findAllUserByRowBounds();
    
    • 1
    • 2
    • 3

    UserMapper.xml

    <select id="findAllUserByRowBounds" resultType="User">
        select * from user
    select>
    
    • 1
    • 2
    • 3

    UserMapperTest.java

    /*
        通过RowBounds类实现分页
     */
    @Test
    public void testUserByRowBounds() {
        SqlSession session = MyBatisUtils.getSqlSession();
        int currentPage = 2;  //第几页
        int pageSize = 2;  //每页显示几个
        RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize,pageSize);
        //通过session.**方法进行传递rowBounds,[此种方式现在已经不推荐使用了]
        List<User> users = session.selectList("com.kuang.dao.UserMapper.findAllUserByRowBounds", null, rowBounds);
        for (User user: users){
            System.out.println(user);
        }
        session.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    测试结果:

    image-20220728104228066

    3、插件实现分页【不推荐】

    MyBatis 分页插件 PageHelper

    如何使用分页插件 (pagehelper.github.io)

    Mybatis分页查询插件PageHelper - 这题我不会 - 博客园 (cnblogs.com)

    8、使用注解开发

    面向接口编程

    • 为什么要面向接口开发?根本原因:解耦

    • 接口原则:就是定义(规范,约束)和实现(名实分离)的分离

    • 接口本身反应系统设计人员对系统的抽象理解

    • 接口应该有两类

      1. 对个体的抽象,对应一个抽象体(abstract class)
      2. 对一个个体某一方面的抽象,即形成一个抽象面(interface)
    • 一个个体可能有多个抽象面,抽象体和抽象面是有区别的

    • 4个面向区别

      1. 面向对象

        是指我们考虑问题时,以对象为单位考虑它的属性和方法

      2. 面向过程

        是指我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现

      3. 面向接口编程

        接口设计和非结构设计是针对复用技术而言的,与面向对象、面向过程 不是一个问题,更多的体现就是对系统整体的架构

        说白了,就是把接口在dao层设计好,对于业务具体实现测试的时候,调用接口中的具体方法就行

      4. 面向切面编程

        说白了,就是好多地方都要用一个方法,重复写就会造成资源浪费,所以提取一个工具类,哪里要用到,哪里调用

    注解开发实例

    查询出所有用户信息

    mybatis-config.xml

    <mappers>
        <mapper class="com.kuang.dao.UserMapper">mapper>
    mappers>
    
    • 1
    • 2
    • 3

    UserMapper.java

    //查询所有用户信息
    @Select("select * from user")
    List<User> getUser();
    
    • 1
    • 2
    • 3

    TestUserMapper.java

    @Test
    public void testGetUser(){
    
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
    
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUser();
        for (User user : userList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    测试结果:

    image-20220728131032123

    注解开发本质

    • 本质:反射机制实现

    • 底层:动态代理模式

      什么是代理?

      帮助真实的对象实现目标

      image-20220728133612565

    9、MyBatis详细执行

    参考图,点击debug,理解一下

    img

    10、注解CRUD

    1. 自动提交事务

      MyBatisUtils.java

      public static SqlSession getSqlSession(){
          // return  sqlSessionFactory.openSession();
          //openSession(autoCommit)  autoCommit设置为true后,就可以自动提交事务,之前的增删改后都需要提交事务,这里改了之后就不需要sqlsession.commit();了
          return  sqlSessionFactory.openSession(true);
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
    2. 编写接口,增加注解

      UserMapper.java

      public interface UserMapper {
      
          //查询所有用户
          @Select("select * from user")
          List<User> getUser();
      
          //查询一个用户
          /*
              方法存在多个参数,所有参数前面需要加上@Param("")注解
              这里 @Param标签绑定user类中的属性名和mysql数据库中的字段名的
              @Param("数据库中的字段名") 类中的属性类型 属性名
           */
          @Select("select * from user where id=#{id} and name=#{name}")
          User getUserByIdAndName(@Param("id") int userid,@Param("name") String username);
      
          //插入一个用户
          @Insert("INSERT INTO USER(id,NAME,pwd)VALUES(#{id},#{name},#{pwd})")
          int addUser(User user);
      
          @Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
          int updateUser(User user);
      
          //删除一个用户
          @Delete("delete from user where id=#{id}")
          int deleteUserById(int id);
      
      
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
    3. 测试类

      【注意】我们必须将接口注册绑定到我们的核心配置文件中!

      MyBatis-config.xml

      
      <mappers>
          <mapper class="com.kuang.dao.UserMapper">mapper>
      mappers>
      
      • 1
      • 2
      • 3
      • 4

      TestUserMapper.java

      public class TestUserMapper {
      
          @Test
          public void testGetUser(){
      
              //底层主要应用反射
              SqlSession sqlSession = MyBatisUtils.getSqlSession();
      
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              List<User> userList = userMapper.getUser();
              for (User user : userList) {
                  System.out.println(user);
              }
      
              sqlSession.close();
          }
      
      
          @Test
          public void testgetUserByIdAndName(){
      
              SqlSession sqlSession = MyBatisUtils.getSqlSession();
      
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              User user = userMapper.getUserByIdAndName(1, "kuangstudy");
              System.out.println(user);
      
              sqlSession.close();
          }
      
          @Test
          public void testAddUser(){
              SqlSession sqlSession = MyBatisUtils.getSqlSession();
      
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              User user = new User(7,"sjf","234");
              int res = userMapper.addUser(user);
              if (res > 0){
                  System.out.println("insert success");
              }
              sqlSession.close();
          }
      
          @Test
          public void testDeleteUserById(){
              SqlSession sqlSession = MyBatisUtils.getSqlSession();
      
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              int res = userMapper.deleteUserById(8);
              if (res > 0){
                  System.out.println("delete success");
              }
              sqlSession.close();
          }
      
          @Test
          public void testUpdateUser(){
              SqlSession sqlSession = MyBatisUtils.getSqlSession();
      
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              User user = new User(7,"sdfjs","dsfa");
              int res = userMapper.updateUser(user);
              if (res > 0){
                  System.out.println("update success");
              }
              sqlSession.close();
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68

    ${}和#{}区别

    • #{} 能防止sql注入

    • ${} 不能防止sql注入,拼接

    • {} 的作用主要是替换预编译语句(PrepareStatement)中的占位符? 【推荐使用】

      INSERT INTO user (name) VALUES (#{name});
      INSERT INTO user (name) VALUES (?);
      
      • 1
      • 2
    • ${} 的作用是直接进行字符串替换

      INSERT INTO user (name) VALUES ('${name}');
      INSERT INTO user (name) VALUES ('kuangshen');
      
      • 1
      • 2

    12、Lambok注解开发插件

    就是将像实体类中get and setter 、有参无参构造方法这些通过注解生成,不需要手动再写;

    有利有弊;

    开发简洁;但可读性降低;

    具体教程网上找:

    1. 到入jar包
    2. 注解开发

    13、复杂查询环境

    多对一:MyBatis-Study/module-06

    一对多:MyBatis-Study/module-07

    多对一处理

    学生和老师的关系:

    image-20220728151823855

    • 多个学生,一个老师
    • 对于学生而言,关联,多个学生,关联一个老师【多对一】
    • 对于老师而言,集合,一个老师,有很多学生【一对多】

    建学生表 老师表 :

    -- 创建teacher表
    CREATE TABLE teacher(
    	id INT(10) NOT NULL,
    	NAME VARCHAR(30) DEFAULT NULL,
    	PRIMARY KEY (id)
    	
    )ENGINE=INNODB DEFAULT CHARSET=utf8
    
    INSERT INTO teacher(id,NAME) VALUES(1,'秦疆')
    
    
    -- 创建student表
    CREATE TABLE student(
    	id INT(10) NOT NULL,
    	NAME VARCHAR(30),
    	tid INT(10) DEFAULT NULL,
    	PRIMARY KEY(id),
    	KEY fktid (tid),
    	CONSTRAINT fktid FOREIGN KEY(tid) REFERENCES teacher(id)
    )ENGINE=INNODB DEFAULT CHARSET=utf8
    
    INSERT INTO student (id, NAME, tid) VALUES ('1', '小窦', '1');
    INSERT INTO student (id, NAME, tid) VALUES ('2', '小五', '1');
    INSERT INTO student (id, NAME, tid) VALUES ('3', '小王', '1');
    INSERT INTO student (id, NAME, tid) VALUES ('4', '小宋', '1');
    INSERT INTO student (id, NAME, tid) VALUES ('5', '小李', '1');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    看一下架构:

    image-20220728154038475

    教师表:

    image-20220728154253158

    学生表:

    image-20220728154315046

    按照查询嵌套处理

    Student.java

    private int id;
    private String name;
    
    //一个学生需要关联一个老师
    private Teacher teacher;
    
    • 1
    • 2
    • 3
    • 4
    • 5

    StudentMapper.xml

    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id">result>
        <result property="name" column="name">result>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher">association>
    resultMap>
    <select id="getStudent" resultMap="StudentTeacher">
        select id, name, tid from student s
    select>
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id=#{tid}
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    testStudentMapper.java

    @Test
    public void getStudent(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = studentMapper.getStudent();
        for (Student student : studentList) {
            System.out.println(student);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    嵌套查询结果:

    image-20220729084107117

    按照结果嵌套处理

    StudentMapper.xml

    
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid, s.name sname, t.name tname from student s, teacher t where s.tid=t.id
    select>
    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="sid">result>
        <result property="name" column="sname">result>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname">result>
        association>
    resultMap>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    testStudentMapper.xml

    @Test
    public void getStudent2(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = studentMapper.getStudent2();
        for (Student student : studentList) {
            System.out.println(student);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试结果:

    image-20220729091848775

    回顾MySql多对一查询方式:

    • 子查询
    • 联表查询

    一对多处理

    比如:一个老师对应多个学生

    对于老师而言,就是一对多的关系!

    按照查询嵌套处理

    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id = #{tid}
    select>
    <resultMap id="TeacherStudent2" type="Teacher">
        
        <collection property="studentList" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId"/>
    resultMap>
    <select id="getStudentByTeacherId" resultType="Student">
        select * from student where tid = #{tid}
    select>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    测试结果:

    @Test
    public void test2(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
    
        TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = teacherMapper.getTeacher2(1);
    
        System.out.println(teacher);
        System.out.println(teacher.getName());
        System.out.println(teacher.getStudentList());
        /*
            秦疆
            [Student{id=1, name='小窦', tid=1},
            Student{id=2, name='小五', tid=1},
            Student{id=3, name='小王', tid=1},
            Student{id=4, name='小宋', tid=1},
            Student{id=5, name='小李', tid=1}]
         */
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    image-20220729111335486

    按照结果嵌套处理

    说白了,就是照着结果进行映射

        
        <select id="getTeacher" parameterType="int" resultMap="TeacherStudent">
            select s.id sid, s.name sname, t.name tname, t.id tid
            from student s,teacher t
            where s.tid = t.id and t.id=#{tid}
        select>
        <resultMap id="TeacherStudent" type="Teacher">
            <result  property="name" column="tname"/>
            <collection property="studentList" ofType="Student">
                <result property="id" column="sid" />
                <result property="name" column="sname" />
                <result property="tid" column="tid" />
            collection>
        resultMap>
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    测试结果:

    @Test
    public void test(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
    
        TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = teacherMapper.getTeacher(1);
    
        System.out.println(teacher);
        System.out.println(teacher.getName());
        System.out.println(teacher.getStudentList());
    
        /*
            秦疆
            [Student{id=1, name='小窦', tid=1},
            Student{id=2, name='小五', tid=1},
            Student{id=3, name='小王', tid=1},
            Student{id=4, name='小宋', tid=1},
            Student{id=5, name='小李', tid=1}]
         */
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    image-20220729111527071

    小结

    1. 关联 - association 【多对一】
    2. 集合 - collection 【一对多】
    3. javaType & ofType
      1. javaType 用来指定实体类中属性的类型
      2. ofType 用来指定映射到List或者集合中的pojo 类型, 泛型中的约束!

    慢sql 1s 1000s

    面试高频

    • mysql引擎
    • innoDB底层原理
    • 索引
    • 索引优化

    14、动态SQL

    什么是动态sql?

    动态sql就是能根据不同的条件生成不同的sql语句;

    官网文档:https://mybatis.org/mybatis-3/zh/dynamic-sql.html

    搭建环境

      -- 动态sql
      -- 创建新表
      CREATE TABLE blog(
    	id VARCHAR(100) NOT NULL COMMENT '博客id',
    	title VARCHAR(100) NOT NULL COMMENT '博客标题',
    	author VARCHAR(30) NOT NULL COMMENT '博客坐着',
    	create_time DATETIME NOT NULL COMMENT '创建时间',
    	views INT(30) NOT NULL COMMENT '浏览量'
      )ENGINE=INNODB DEFAULT CHARSET=utf8
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    MyBatis-Study/mybaits-08

    Blog.java

    package com.kuang.pojo;
    
    import java.sql.Date;
    
    public class Blog {
    
        private int id;
        private String title;
        private String author;
        private Date createTime;
        private int views; //浏览量
    
        public Blog() {
        }
    
        public Blog(int id, String title, String author, Date createTime, int views) {
            this.id = id;
            this.title = title;
            this.author = author;
            this.createTime = createTime;
            this.views = views;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getAuthor() {
            return author;
        }
    
        public void setAuthor(String author) {
            this.author = author;
        }
    
        public Date getCreate_time() {
            return createTime;
        }
    
        public void setCreate_time(Date createTime) {
            this.createTime = createTime;
        }
    
        public int getViews() {
            return views;
        }
    
        public void setViews(int views) {
            this.views = views;
        }
    
        @Override
        public String toString() {
            return "Blog{" +
                    "id=" + id +
                    ", title='" + title + '\'' +
                    ", author='" + author + '\'' +
                    ", createTime=" + createTime +
                    ", views=" + views +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    IF

    
    <select id="queryBlogIF" resultType="Blog">
        select * from blog where 1=1
        <if test="title != null">
            and title = #{title}
        if>
        <if test="author != null">
            and author = #{author}
        if>
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    choose when otherwise

    //查询博客 choose
    List<Blog> queryBlogChoose(Map map);
    
    • 1
    • 2
    
    <select id="queryBlogChoose" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <choose>
                <when test="title != null">
                    AND title like #{title}
                when>
                <when test="author != null and author.name != null">
                    AND author_name like #{author.name}
                when>
                <otherwise>
                    AND featured = 1
                otherwise>
            choose>
        where>
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    trim whre set

    //更新博客 set
    int updateBlog(Map map);
    
    • 1
    • 2
    <update id="updateBlog" parameterType="map">
        update blog
        <set>
            <if test="title != null">
                title = #{title}
            if>
            <if test="author != null">
                author = #{author}
            if>
        set>
        where id = #{id}
    update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    所谓的动态sql,本质还是sql语句,只是我们可以在sql层面,执行一个逻辑代码

    if

    where

    set

    choose

    foreach

    select * from user where 1=1 and 
    (id=1 or id=2 or id=3)
    
    • 1
    • 2
    select * from user where 1=1 and 
    
    	id = #{id}
    
    
    • 1
    • 2
    • 3
    • 4
    //查询第1-2-3号记录的博客
    List<Blog> queryBlogForeach(Map map);
    
    • 1
    • 2
    
    <select id="queryBlogForeach" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            foreach>
        where>
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    @Test
    public void queryBlogForeach(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
    
        HashMap map = new HashMap();
    
        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
    
        map.put("ids", ids);
        List<Blog> blogs = blogMapper.queryBlogForeach(map);
    
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    
        sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    image-20220801100225770

    image-20220801101810369

    image-20220801095453595

    sql片段

    有的时候,可以将一部分功能抽取出来,方便复用!

    1. 使用SQL标签抽取公共部分

      <sql id="if-title-author">
          <if test="title != null">
              and title = #{title}
          if>
          <if test="author != null">
              and author = #{author}
          if>
      sql>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
    2. 在需要使用的地方include标签引用即可

      <select id="queryBlogIF" resultType="Blog">
          select * from blog
          <where>
              <include refid="if-title-author">include>
          where>
      select>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6

    注意:

    • 最好基于单表来定义sql片段
    • 不要存在where标签

    建议:

    • 先在mysql中写出完整的sql,再对应地修改为我们的动态sql,实现通用即可!

    15、缓存

    什么是缓存?

    查询 连接数据库 耗费资源!

    一个查询的结果,能够暂存在一个直接能取到的地方! --> 内存 缓存!

    我们再次查询相同的数据的时候,直接走缓存,就不用走数据库了!

    不用开启连接,不用关闭连接…

    • 缓存是存在内存中的临时数据
    • 将用户经常查询的数据放到内存(缓存)中,用户去查询的数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

    为什么使用缓存?

    • 减少与数据库的交互次数
    • 减少系统开销
    • 提高系统效率

    为什么数据库能使用缓存?

    • 经常查询,且不经常改变的数据

    image-20220801103638064

    Mybatis缓存?

    • mybatis包含一个非常强大的查询缓存特性,可以非常方便地定制和配置缓存

    • 缓存可以极大地提升查询效率

    • MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存

      默认情况下,只有一级缓存开启,(sqlsession级别的缓存,也称为本地缓存)

      二级缓存需要手动开启和配置,他是基于namespace级别的缓存

      为了提高扩展性,MyBatis定义了缓存接口Cache,可以通过实现Cache接口来自定义二级缓存

    一级缓存

    • 一级缓存 也叫本地缓存,sqlsession 本地会话缓存
      • 与数据库同义词会话期间查询到的数据会放到本地缓存中
      • 以后如果需要获得相同的数据,直接从缓存中拿,没有必要再去查询数据库
      • 一级缓存默认开启
      • 手动清除缓存 sqlsession.claerCache();
      • 一级缓存就想相当于一个map

    测试:

    查询user表中的一条信息,第一次查询和第二次查询的区别:

    UserMapper.java

    User queryUserById(@Param("id") int id);
    
    • 1

    UserMapper.xml

    <select id="queryUserById" parameterType="int" resultType="User">
        select * from user where id = #{id}
    select>
    
    • 1
    • 2
    • 3

    test.java

    @Test
    public void testQueryUserById(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    
        User user = userMapper.queryUserById(1);
        System.out.println(user);
    
        System.out.println("==============================");
        User user2 = userMapper.queryUserById(1);
        System.out.println(user2);
    
        sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    测试结果:image-20220801112038102

    //测试两次查询出来的user相等
    System.out.println(user==user2);  //true
    
    • 1
    • 2

    image-20220801130412493

    注意:对于 增删改 操作,可能会不改变原来的数量,所以必定会刷新缓存!

    修改id=2的用户数据,并查询id=1的用户数据;

        @Test
        public void testQueryUserById(){
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    
            User user = userMapper.queryUserById(1);
            System.out.println(user);
    
            userMapper.updateUser(new User(2,"dason","1232"));
    
            System.out.println("==============================");
            User user2 = userMapper.queryUserById(1);
            System.out.println(user2);
    
            //测试两次查询出来的user相等
            System.out.println(user==user2);  //true
    
            sqlSession.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    测试结果:

    修改一条数据后,一级缓存中就会刷新缓存,再进行第二次查询时就会再去数据库中查找。缓存失效!

    image-20220801131431782

    二级缓存

    • 二级缓存 默认开启 ,也叫全局缓存,作用域更高了

    • 开启二级缓存 在 UserMapper.xml 中加入标签

    • 工作机制:

      • 一个会话查询一条数据,这个数据就会被放在当前会话中的一级缓存中
      • 如果当前会话关闭了,这个会话对应的以及缓存就没了;但是我们想要的是,会话关闭了。以及缓存中的数据就会被保存在二级缓存中去
      • 新的会话查询信息,就可以从二级缓存中获取数据
      • 不同的mapper查出的数据会放在自己对应的缓存(map)中
    • 标签中还可以定义一些功能

      xml文件:

          
          <cache
              eviction="FIFO"
              flushInterval="60000"
              size="512"
              readOnly="true"
          />
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12

      javaAPI:

      使用 @CacheNamespaceRef 注解指定缓存作用域

    • 使用步骤:

      1. 开启缓存

        mybatis-config.xml

        
        <setting name="cacheEnable" value="ture"/>
        
        • 1
        • 2

        image-20220801140051410

      2. 在要使用二级缓存的Mapper中开启

        UserMapper.xml

            
            <cache/>
        
        
            
            <cache
                eviction="FIFO"
                flushInterval="60000"
                size="512"
                readOnly="true"
            />
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
        • 16

        image-20220801140232532

      3. 测试

        通过两个sqlsession查询id=1的用户信息,这时查询两次,与数据库交互两个;

        而开启二级缓存后,在第一个sqlsession查完后,关闭sqlsession会话,这个会话信息就会存储到二级缓存中,第二次查询的时候会从二级缓存中获取,不会再和数据库进行交互!

        1. 问题: 需要将实体类序列化,否则会报错!

          报错: Caused By: java.io.NotSerializableException:com.kuang.pojo.user

          public class User implements Serializable {
          
          • 1
    • 小结:

      • 只要开启了二级缓存,在同一个Mapper下就有效
      • 所有的数据都会先放在一级缓存下
      • 只有当会话提交,或者关闭时候,才会提交到二级缓存中
      • 实体类序列化是应为实体在二级缓存中,所以需要序列化的处理才能方便查找
      • 会话关闭or提交后,数据先放在一级缓存中,再放到二级缓存中;用户查询数据,先从二级缓存中查,然后再去一级缓存中查询,最后去数据库中查;

    缓存失效的情况

    1. 查询不同的东西
    2. 增删改 操作,可能会改变原来的数据,所以必定会刷新缓存!
    3. 查询不同的Mapper.xml
    4. 手动清除缓存 sqlSession.clearCache();//手动清除一级缓存(本地缓存 sqlsession)

    缓存策略?

    • LRU – 最近最少使用:移除最长时间不被使用的对象。 least recently used
    • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。 first in , first out
    • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
    • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。

    默认的清除策略是 LRU。

    MyBatis缓存原理?

    image-20220801145743301

    自定义缓存-ehcache

    EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

    使用步骤:

    1. 导mybatis-ehcache 的jar包
    2. 开启定义的cache,在mapper指定使用自定义的 ehcache 缓存实现
    3. 建立ehcache.xml配置文件

    引用缓存-refcache

    <cache-ref namespace=""/>
    
    • 1
  • 相关阅读:
    读了很多书,学了很多语言,专业知识远超普通大众,程序员1024依然要送外卖
    Vue-admin-template新增TagViews标签页功能,附完整代码
    jenkins-用户权限管理
    Provide 和 Inject 的用法
    第五章:方法
    Cross-species regulatory sequence activity prediction
    SpringBoot多数据源以及事务处理
    PCL 计算两空间直线的交点
    <C++>学习:类与对象
    终于升级?89年Linux内核C语言“跟上时代”转成现代C
  • 原文地址:https://blog.csdn.net/MS_SONG/article/details/126102911