【MyBatis】mybatis笔记(全)

MyBatis

1. 简介

1.1 什么时Mybatis

logo

  • MyBatis 是一款持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射。
  • MyBatis 免除了几乎所有的 JDBC 代码以及 设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

1.2 获取Mybatis

  • Maven仓库:

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    
  • Github: https://github.com/mybatis/mybatis-3/releases

  • 中文文档:https://mybatis.org/mybatis-3/zh/index.html

1.3 持久层

数据持久化:

  • 将数据持久的存储在某个地方,例如:将内存的数据存储到硬盘,数据库,io文件(以前)

持久层:

  • Dao层

  • 用来完成持久化工作的代码

1.4 Mybatis优势

  • 简单易学
  • 灵活
  • 解除sql与程序代码的耦合
  • 提供映射标签,支持对象与数据库的orm字段关系映射
  • 提供对象关系映射标签,支持对象关系组建维护
  • 提供xml标签,支持编写动态sql。

2. 第一个Mybatis程序

2.1 环境搭建

新建数据库
create database if not exists mybatis default charset=utf8;

use mybatis;

create table `user`(
	id int(20) not null auto_increment primary key,
	`name` varchar(30) default null,
	`pwd` varchar(30) default null
)ENGINE=INNODB default charset=utf8;

insert into `user`(`name`,`pwd`) VALUES
("张三","123456"),
("李四","123456"),
("王五","123456")
新建项目
  • 新建普通Maven项目

    在这里插入图片描述

    在这里插入图片描述

  • 删除src目录(父工程: 方便练习学习,不用多次创建项目)

    在这里插入图片描述

  • 在父工程的pom.xml中导入依赖

    	<dependencies>
            <!--    Mysql驱动    -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.22</version>
            </dependency>
            <!--    mybatis    -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.6</version>
            </dependency>
            <!--    junit 单元测试    -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
            </dependency>
        </dependencies>
    

    注:如果依赖包名报红,点击idea侧边栏上的maven后,点击刷新

    在这里插入图片描述

    项目搭建完毕

2.2 创建一个子模块

  • 在父项目右键新建一个模块(子工程)

    这样可以不用每次都导包了

在这里插入图片描述

  • 再次创建一个普通maven项目

    在这里插入图片描述

在这里插入图片描述

编写mybatis核心配置文件
  • 在mybatis01/src/main/resources下新建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核心配置文件-->
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=ture&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"/>
                    <property name="username" value="root 你的数据库用户名"/>
                    <property name="password" value="你的数据库密码"/>
                </dataSource>
            </environment>
        </environments>
    <!-- 注意每个mapper.xml都要在此处注册 -->
    </configuration>
    
编写mybatis工具类
  • 在mybatis01/src/main/java下创建自己的包路径

    在这里插入图片描述

  • 工具类

    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 (IOException e) {
                e.printStackTrace();
            }
        }
    
        //有了 SqlSessionFactory,我们可以从中获得 SqlSession 的实例.
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法.
        public static SqlSession getSession(){
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;
        }
    }
    

2.3 编写代码

实体类
  • entity包下 User类
package com.nych.entity;

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;
    }

    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 + '\'' +
                '}';
    }
}

Dao (或mapper) 接口
public interface UserDao {
    List<User> getUserList();
}
接口实现类: 由以前的类转换为xml文件:
  • UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace= 绑定一个对应的dao/mapper接口-->
<mapper namespace="com.nych.dao.UserDao">
    <!--  查询 id对应方法名 resultType = 返回类型 -->
    <select id="getUserList" resultType="com.nych.entity.User">
        select * from `user`
    </select>
</mapper>
  • namespace: 对应一个要实现的接口
  • id: 对应接口中的方法名
  • resultType: 返回结果类型
  • 还有一个 parameterType: 参数类型; 会在后面用到

2.4 编写测试类

  • 在test下建立和源码同样的文件目录

    在这里插入图片描述

测试代码
  • junit测试
public class UserDaoTest {

    @Test
    public void test(){
        //第一步: 获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSession();
        //方式一: getMapper(推荐使用)
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();

        //方式二: (不推荐使用)
        List<User> userList2 = sqlSession.selectList("com.nych.dao.UserDao.getUserList");

        for (User user : userList) {
            System.out.println(user);
        }

        System.out.println("---------------------------------------------");

        for (User user : userList2) {
            System.out.println(user);
        }
        //关闭sqlSession
        sqlSession.close();
    }

}
错误解析
  • org.apache.ibatis.binding.BindingException: Type interface com.nych.dao.UserDao is not known to the MapperRegistry.
  • mapper.xml没有在核心配置文件中注册
    • 每一个mapper.xml都需要在核心配置文件中注册
      <mappers>
          <mapper resource="com/nych/dao/UserMapper.xml"/>
      </mappers>
    • Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/nych/dao/UserMapper.xml
    • Could not find resource com/nych/dao/UserMapper.xml
    • maven文件导出问题,找不到UserMapper.xml

    • 解决: 需要在pom.xml中添加以下代码

      	<build>
              <resources>
                  <resource>
                      <directory>src/main/resources</directory>
                      <includes>
                          <include>**/*.properties</include>
                          <include>**/*.xml</include>
                      </includes>
                      <filtering>true</filtering>
                  </resource>
                  <resource>
                      <directory>src/main/java</directory>
                      <includes>
                          <include>**/*.properties</include>
                          <include>**/*.xml</include>
                      </includes>
                      <filtering>true</filtering>
                  </resource>
              </resources>
          </build>
      
    • 注意:添加代码后需要刷新Maven。

  • Error creating document instance. Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。

  • 需要删除xml文件中的中文注释

    • 或 将xml文件的encoding=“UTF-8”改成encoding=“UTF8”
测试结果

在这里插入图片描述

总结

写Mybatis的步骤:

  • 在Maven中添加依赖包

  • 编写获取SqlSession对象的工具类

  • 工具类中需要mybatis 核心配置文件(mybatis-config.xml)

  • 编写User表的实体类User.java

  • 编写操作User的接口UserDao/UserMapper(interface)

  • 编写实现UserDao/UserMapper的实现 UserDao.xml / UserMapper.xml

  • 写测试类测试代码

3. Mybatis CRUD

  • 增加(Create)、检索(Retrieve)、更新(Update)和删除(Delete)

3.1 insert©

  • 需求: 新增一名用户

    • 实现: 在UserMapper/UserDao中写一个抽象方法

          //新增一个用户
          int addUser(User user);
      
    • 在userMapper.xml中实现该抽象方法

      <!-- 新增用户 -->
      <insert id="addUser" parameterType="com.nych.entity.User">
          insert into mybatis.user (`name`,`pwd`) values (#{name},#{pwd})
      </insert>
      
  • 测试

    • 注意: 增、删、改 三个操作都需要提交事务

      //增删改 需要提交事务
      //新增用户测试
      @Test
      public void addUser(){
          SqlSession sqlSession = MybatisUtils.getSession();
          UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      
          User user = new User("新用户","000000");
          int i = userMapper.addUser(user);
          //提交
          sqlSession.commit();
          
          if(i > 0){
              System.out.println("成功添加了"+ i +"个用户!");
          }else{
              System.out.println("添加用户失败!");
          }
          
          //关闭
          sqlSession.close();
      }
      
    • 测试结果

      在这里插入图片描述

3.2 select®

  • 需求: 根据id查用户

    • 实现:在UserDao/UserMapper中添加抽象方法:

      //根据id查询
      User getUserById(int id);
      
    • 在UserMapper.xml中实现接口中的抽象方法

      <select id="getUserById" parameterType="int" resultType="com.nych.entity.User">
          select * from `user` where id = #{id}
      </select>
      
    • parameterType: 参数类型

  • 测试

        //测试根据id查用户
        @Test
        public void getUserById(){
            SqlSession sqlSession = MybatisUtils.getSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    
            User user = userMapper.getUserById(1);
            System.out.println("user = " + user);
            
            sqlSession.close();
        }
    
  • 测试结果

    在这里插入图片描述

3.3 update(U)

  • 需求: 修改一个用户

    • 实现: 在UserDao/UserMapper中添加一个抽象方法

      //修改用户
      int updateUser(User user);
      
    • 在UserMapper.xml中实现这个抽象方法

      <!--修改用户信息-->
      <update id="updateUser" parameterType="com.nych.entity.User">
          update mybatis.user set `name` = #{name},`pwd` = #{pwd} where id = #{id}
      </update>
      
  • 测试

    //测试修改
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    
        User user = new User(5,"修改新用户","111111");
        int i = userMapper.updateUser(user);
    	sqlSession.commit();
        
        if(i > 0){
            System.out.println("成功修改了" + i + "个用户!");
        }else{
            System.out.println("修改用户失败!");
        }
        
        //关闭
        sqlSession.close();
    }
    
    • 测试结果

      在这里插入图片描述

3.4 delete(D)

  • 需求:根据id删除一个用户

    • 实现: 在UserDao/UserMapper中添加一个抽象方法

      //删除一个用户
      int deleteUser(int id);
      
    • 在UserMapper.xml中实现这个抽象方法

      <!--  删除一个用户  -->
      <delete id="deleteUser" parameterType="int">
          delete from `user` where id = #{id}
      </delete>
      
  • 测试

    • 测试代码

      //测试删除
      @Test
      public void deleteUser(){
          SqlSession sqlSession = MybatisUtils.getSession();
          UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      
          int i = userMapper.deleteUser(5);
      
          if(i > 0){
              System.out.println("成功删除了" + i + "个用户!");
          }else{
              System.out.println("删除用户失败!");
          }
      
          sqlSession.commit();
          //关闭
          sqlSession.close();
      }
      
    • 测试结果

      在这里插入图片描述

3.5 使用Map传递参数

  • 如果数据库中字段很多,实体类中的参数也很多,那么使用实体类对象来传参就不是很方便了,此时可以考虑使用Map!
    • 使用map传参,直接在sql中使用map的key即可取出参数。
    • 使用对象传参,直接在sql中使用对象的属性名即可取出参数。

3.5.1 使用Map传递参数,实现添加用户

  • 在UserDao/UserMapper中添加一个抽象方法

    //添加用户 map方法
    int addUser2(Map<String, Object> map);
    
  • 在UserMapper.xml中实现这个抽象方法

    <!--  新增用户 Map方法  -->
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user (`name`,`pwd`) values (#{username},#{password})
    </insert>
    
  • 测试

        @Test
        public void addUser2(){
            SqlSession sqlSession = MybatisUtils.getSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            Map<String, Object> map = new HashMap<>();
    
            map.put("username","张三");
            map.put("password","222222");
    
            int i = mapper.addUser2(map);
            if(i > 0){
                System.out.println("成功插入"+ i + "个用户!");
            }else {
                System.out.println("插入失败");
            }
            sqlSession.commit();
            sqlSession.close();
        }
    
  • 测试结果

    在这里插入图片描述

3.5.2 使用Map传递参数,实现查询用户

  • 在UserDao/UserMapper中添加一个抽象方法

        //根据id查用户 Map方法
        User getUserById2(Map<String, Object> map);
    
  • 在UserMapper.xml中实现这个抽象方法

    <select id="getUserById2" parameterType="map" resultType="com.nych.entity.User">
        select * from `user` where id = #{userId} and `name` = #{userName}
    </select>
    
  • 测试

    //测试 使用Map传参
    @Test
    public void getUserById2(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        Map<String, Object> map = new HashMap<>();
    
        map.put("userId",6);
        map.put("userName","张三");
    
        User user = mapper.getUserById2(map);
    
        System.out.println("user = " + user);
    
        sqlSession.commit();
        sqlSession.close();
    }
    
  • 测试结果

    在这里插入图片描述

3.6 Mybatis模糊查询

传递字符串"%xxx%"
  • 在UserDao/UserMapper中添加一个抽象方法

    //模糊查询
    List<User> getUserLike(String value);
    
  • 在UserMapper.xml中实现这个抽象方法

    <!--  模糊查询用户  -->
    <select id="getUserLike" resultType="com.nych.entity.User">
        select * from `user` where `name` like #{value}
    </select>
    
  • 测试

    //测试 模糊查询1
    @Test
    public void getUserLike(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        String getUsername = "张";   //假如是从前端获取到的数据
    
        List<User> userList = mapper.getUserLike("%"+getUsername+"%");
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    
在SQL中拼接通配符
  • 注意防止sql注入
select * from `user` where `name` like "%"#{value}"%";

4. 配置解析

4.1 核心配置文件

4.2 环境配置(environments)

  • MyBatis 可以配置成适应多种环境

  • 尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

    <environments default="test">
        <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=ture&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </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>
    
4.2.1 事务管理器(transactionManager)
  • 在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC | MANAGED]")默认: JDBC

  • JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。

  • MANAGED – 这个配置几乎没做什么。它从不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接。然而一些容器并不希望连接被关闭,因此需要将 closeConnection 属性设置为 false 来阻止默认的关闭行为。

<transactionManager type="JDBC"/>
4.2.2 数据源(dataSource)
  • 有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]") 默认: POOLED

4.3 属性(properties)

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

**编写数据库配置文件: **

  • 在resources下新建 db.properties:
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?
	useSSL=true&useUnicode=ture&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username = root
password = 123456

在核心配置文件(mybatis-config.xml)中引入:

<!--  引入配置文件: 只能写在顶部  -->
<properties resource="db.properties">
    <!--内部定义变量: 如果有相同变量名, 优先使用引入的配置 -->
    <property name="password" value="123456"/>
</properties>

引入后即可在配置文件中使用:

<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>

4.4 typeAliases(类型别名)

  • 类型别名可为 Java 类型设置一个缩写名字。

    <typeAliases>
        <!-- 给类起别名 -->
        <typeAlias alias="User" type="com.nych.entity.User"/>
    </typeAliases>
    
  • 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

<typeAliases>
    <!--扫描entity包,以entity包中类名为别名(首字母小写)-->
	<package name="com.nych.entity"/>
</typeAliases>
  • 每一个在包 com.nych.entity 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 com.nych.entity.User 的别名为 user;

  • 若有注解,则别名为其注解值。

```java
@Alias("别名")
public class User{
    ...
}
```
  • 设置好别名后,即可在其它地方使用该别名, 如:

    <select id="getUserList" resultType="user">
        select * from `user`
    </select>
    

4.5 设置(settings)

  • 这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置

4.6 其他配置

4.7 映射器

  • MapperRegistry: 在核心配置文件(mybatis-config.xml) 中注册UserMapper.xml文件

  • 注册方法一:

        <mappers>
            <mapper resource="com/nych/dao/UserMapper.xml"/>
        </mappers>
    
  • 注册方法二:使用class

    • 接口和mapper.xml必须同名
    • 接口和mapper.xml必须在同一个包下
        <mappers>
            <mapper class="com.nych.dao.UserMapper"/>
        </mappers>
    
  • 注册方法三:使用包扫描

    • 接口和mapper.xml必须同名
    • 接口和mapper.xml必须在同一个包下
        <mappers>
            <package name="com.nych.dao"/>
        </mappers>
    

4.8 作用域和生命周期

  • 不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。

SqlSessionFactoryBuilder:

  • 一旦创建了SqlsessionFactory,就不在需要它了
  • 那么最好把它定义为局部变量(方法作用域)

SqlsessionFactory:

  • 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例

  • 因此 SqlSessionFactory 的最佳作用域是应用作用域。

  • 最简单的就是使用单例模式或者静态单例模式。

Sqlsession:

  • 每个线程都应该有它自己的 SqlSession 实例。
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域 。
  • 使用完毕,立即关闭( 最好放在finally 块 )。

5. ResultMap

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

  • 数据库中的字段

    在这里插入图片描述

  • 新建项目

    • 实体类中的字段

      public class User {
          private int id;
          private String name;
          private String password;
      }
      
  • 测试

        @Test
        public void testGetUserList(){
            SqlSession sqlSession = MybatisUtils.getSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            User user = mapper.getUserById(1);
    
            System.out.println(user);
    
            sqlSession.close();
        }
    
  • 测试结果: 查不出password

在这里插入图片描述

select * from `user` where id = #{id};
			||
select id,name,pwd from `user` where id = #{id};
  • 解决方式一:起别名

    select id,name,pwd as password from `user` where id = #{id};
    
  • 解决方式二:

    • resultMap

      结果集映射

          <!--  结果集映射  -->
          <resultMap id="userMap" type="User">
              <!-- column:数据库中的字段, property: 实体类中的属性 -->
              <result column="pwd" property="password"/>
          </resultMap>
      
          <select id="getUserById" resultMap="userMap">
              select * from `user` where id = #{id}
          </select>
      
    • resultMap 元素是 MyBatis 中最重要最强大的元素。

    • resultMap 能够代替实现同等功能的数千行代码。ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

6. 日志

6.1 日志工厂

  • 对数据库进行操作,出现了异常,我们可以使用日志进行排错。
设置名描述有效值默认值
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置
  • STDOUT_LOGGING:

        <settings>
        <!-- 标准日志 -->
            <setting name="logImpl" value="STDOUT_LOGGING"/>
        </settings>
    

    输出的日志:

    Opening JDBC Connection
    Created connection 1259652483.
    Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4b14c583]
    ==>  Preparing: select * from `user` where id = ?
    ==> Parameters: 1(Integer)
    <==    Columns: id, name, pwd
    <==        Row: 1, 张三, 123456
    <==      Total: 1
    User{id=1, name='张三', password='123456'}
    Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4b14c583]
    Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4b14c583]
    Returned connection 1259652483 to pool.
    

6.2 LOG4J

6.2.1 LOG4J是什么
  • log for java

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;

6.2.2 使用LOG4J:
  • 导包

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
  • 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/nych.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
    
  • 设置日志以log4j实现

    <!--  设置  -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    
  • LOG4J的使用

    • 直接运行测试

      在这里插入图片描述

    • 简单使用

      • 在要使用LOG4J的类中,导入org.apache.log4j.Logger

      • 创建日志对象,参数为当前类的class

        static Logger logger = Logger.getLogger(UserMapperTest.class);
        
      • 日志级别

        logger.info("info:进入testLOG4J");
        logger.debug("debug:进入了testLOG4J");
        logger.error("error: 进入了testLOG4J");
        

7. Mybatis实现分页

  • 分页可以减少数据查询时间,提高效率

7.1 使用Limit分页

  • sql语法
select * from `user` limit start,size

select * from `user` limit 0,3;
		||
select * from `user` limit 3;
  • 接口
//分页
List<User> getUserLimit(Map<String, Integer> map);
  • 实现接口(UserMapper.xml)
<select id="getUserLimit" parameterType="map" resultMap="userMap">
    select * from `user` limit #{start},#{size}
</select>
  • 测试
@Test
public void testLimit(){
    SqlSession sqlSession = MybatisUtils.getSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("start",0);
    map.put("size",2);

    List<User> userList = userMapper.getUserLimit(map);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

7.2 使用RowBounds分页

不推荐使用

  • 接口
List<User> getUserByRowBounds();
  • mapper.xml
<select id="getUserByRowBounds" resultMap="userMap">
    select * from `user`
</select>
  • 测试
@Test
public void testRowBounds(){
    SqlSession sqlSession = MybatisUtils.getSession();

    RowBounds rowBounds = new RowBounds(1,3);

    List<User> userList = sqlSession.selectList("com.nych.dao.UserMapper.getUserByRowBounds", null, rowBounds);

    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

7.3 分页插件

pageHelper

8. Mybatis注解开发

8.1 注解的基本用法

  • 使用注解来映射简单语句会使代码显得更加简洁
  • 但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪
  • 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句

接口:

    //获取全部用户
	@Select("select * from user")
    List<User> getUserList();

	//根据用户id查用户
	@Select("select * from user where id = #{id}")
	User getUserById();

在核心配置中注册该类:

    <mappers>
        <mapper class="com.nych.dao.UserMapper"/>
    </mappers>

测试:

    @Test
    public void testGetUserList(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

实现方法:反射机制实现

底层:动态代理

8.2 注解实现CRUD

将SQL改成自动提交:

public static SqlSession getSession(){
    //openSession(true) 开启自动提交
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    return sqlSession;
}

接口加注解:

public interface UserMapper {
    
    @Select("select * from user")
    List<User> getUserList();

    //根据id查找用户
    //@Param()注解在多个参数的时候,需要加上; 它可以指定参数名称
    @Select("select id,name,pwd as password from `user` where id = #{userId}")
    User getUserById(@Param("userId") int id);

    //使用注解添加一个用户
    //引用类型不需要加Param注解
    @Insert("insert into `user` (name,pwd) values(#{name},#{password})")
    int addUser(User user);

    //使用注解修改一个用户
    @Update("update `user` set `name` = #{name}, `pwd` = #{password} where id = #{id}")
    int updateUser(User user);

    //使用注解删除一个用户
    @Delete("delete from `user` where id = #{id}")
    int deleteUser(@Param("id") int id);

}

@Param注解:

  • 基本类型或String 类型,需要加上
  • 引用类型不需要加
  • 只有一个参数的时候,可以忽略,建议加上
  • sql中引用的参数是@Param中定义的属性名

#{} 和 ${}的区别:

  • #{} 占位符 :动态解析 -> 预编译 -> 执行
  • ${} 拼接符 :动态解析 -> 编译 -> 执行
  • #{} 对应的变量 会 自动加上单引号
  • ${} 对应的变量 不会 加上单引号
  • #{}能防止sql 注入
  • ${}不能防止sql 注入
  • 能用 #{} 的地方就用 #{}

测试:

public class UserMapperTest {
    
    //查询全部用户
    @Test
    public void testGetUserList(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> userList = mapper.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }

        sqlSession.close();
    }

    //根据id查询用户
    @Test
    public void testGetUserById(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.getUserById(1);

        System.out.println(user);

        sqlSession.close();
    }

    //添加用户
    @Test
    public void testAddUser(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = new User("注解", "123456");
        int i = userMapper.addUser(user);

        if(i > 0){
            System.out.println("成功添加了 " + i + " 个用户!");
        }else {
            System.out.println("添加用户失败!");
        }

        sqlSession.close();
    }

    //修改用户
    @Test
    public void testUpdateUser(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = new User(3,"注解修改", "123456");
        int i = userMapper.updateUser(user);

        if(i > 0){
            System.out.println("成功修改了 " + i + " 个用户!");
        }else {
            System.out.println("修改用户失败!");
        }

        sqlSession.close();
    }

    //删除用户
    @Test
    public void testDeleteUser(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        int i = userMapper.deleteUser(3);

        if (i > 0){
            System.out.println("成功删除了 " + i + " 个用户!");
        }else {
            System.out.println("删除用户失败!");
        }
        sqlSession.close();
    }

}

注意:接口需要在核心配置文件中注册

9. Lombok插件

9.1 简介

Project Lombok 是一个 Java 库,可自动插入您的编辑器并构建工具,为您的 Java 增添趣味。
永远不要再编写另一个 getter 或 equals 方法,通过一个注释,您的类就有一个功能齐全的构建器,自动化您的日志变量等等。

9.2 使用方法

  1. 在IDEA中下载安装Lombok插件

    • 在file -> settings -> plugins 中搜索lombok安装即可。
  2. 使用Maven导入lombok的jar包

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
    
  3. 使用

    • @Data: 自动生成了无参构造,get, set, toString, hasacode, equals
  • @AllArgsConstructor: 生成有参构造
    • @NoArgsConstructor:生成无参构造

10. 多对一

  • 多个学生,对应一个老师
  • 对于学生来说,多个学生关联一个老师(多对一)
  • 对于老师来说,集合,一个老师有多个学生(一对多)

10.1 环境搭建

新建数据表:

SQL:

create table `teacher`(
	id int(10) not null primary key auto_increment,
	`name` varchar(30) default null
)ENGINE = INNODB default charset=utf8;

insert into `teacher` (`name`) values
('张老师'),
('李老师');

create table `student`(
	id int(10) not null primary key auto_increment,
	`name` varchar(30) default null,
	`tid` int(10) default null,
	key `fktid` (`tid`),
	CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher`(`id`)
)ENGINE = INNODB default charset=utf8;


insert into `student` (`name`,`tid`) VALUES
('小明',1),
('小红',1),
('小强',1),
('小王',1);

新建maven项目

新建实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;
    //学生需要关联一个老师
    private Teacher teacher;
}

写mapper接口

写mapper.xml

在配置文件中注册mapper接口或xml文件

测试环境

10.2 嵌套查询方式

<resultMap id="StudentAndTeacher" type="student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--   result 只能处理单个属性,复杂属性,需要单独处理
        对象: association
        集合: collection
        -->
    <association property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>

<select id="getStudents" resultMap="StudentAndTeacher">
    select * from student
</select>

<select id="getTeacher" resultType="teacher">
    select * from teacher where id = #{tid}
</select>

10.2 按照结果嵌套处理

<!--  有外键的多表查询: 方法二:  -->

<resultMap id="StudentAndTeacher2" type="student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
    </association>
</resultMap>

<select id="getStudents2" resultMap="StudentAndTeacher2">
    select s.id as sid, s.name as sname, tid, t.name as tname from student as s, teacher as t where s.tid = t.id
</select>

Mysql多对一查询方式:

- 子查询(嵌套查询)
- 联表查询

11. 一对多

一个老师有多个学生,对老师而言就是一对多的关系

11.1 环境搭建

实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;
    private int tid;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
}

11.2 方法一

<resultMap id="TeacherAndStudents" type="teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--    一对多:集合使用 collection 使用 ofType-->
    <collection property="students" ofType="student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

<select id="getTeacher" resultMap="TeacherAndStudents">
    select s.id as sid, s.name as sname, t.id as tid, t.name as tname
    from student as s, teacher as t
    where t.id = s.tid and t.id = #{tid}
</select>

11.2 方法二

<resultMap id="TeacherAndStudents2" type="teacher">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <collection property="students" column="id" javaType="ArrayList" ofType="student" select="getStudent"/>
</resultMap>

<select id="getTeacher2" resultMap="TeacherAndStudents2">
    select * from teacher where id = #{tid}
</select>

<select id="getStudent" resultType="student">
    select * from student where tid = #{id}
</select>

11.3 总结

  1. 关联 association(多对一)
  2. 集合 collection (一对多)
  3. javaType 和 ofType
    • javaType 用来指定实体类总属性的类型
    • ofType 用来指定映射到List或集合中的pojo类型,泛型中的约束类型

12. 动态SQL

根据不同的条件生成不同的sql语句

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

12.1 环境搭建

  • 创建数据库

    CREATE TABLE `blog`(
    `id` int(30) NOT NULL primary key auto_increment 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;
    

12.2 if

<!-- if 查询  -->
<select id="queryBlogIf" parameterType="map" resultType="blog">
    select * from mybatis.blog where 1 = 1
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</select>

或:

<select id="queryBlogIf" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>

12.3 choose

  • choose (when, otherwise)

  • 类似于switch(case, default)

<!--  choose 查询  -->
<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                author = #{author}
            </when>
            <otherwise>
                views > #{views}
            </otherwise>
        </choose>
    </where>
</select>

12.4 trim (where, set)

Set:

  • 动态的在语句前添加set关键字
  • 自动删除无用的逗号
<!--  更新  -->
<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author},
        </if>
        <if test="views != null">
            views = #{views},
        </if>
    </set>
    where id = #{id};
</update>

Where:

  • 如果只有一个条件,可以不写and
select * from blog
    <where>
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                author = #{author}
            </when>
            <otherwise>
                views > #{views}
            </otherwise>
        </choose>
    </where>
  • 如果可能有多个条件,可以去除多余的and
<select id="queryBlogIf" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>

trim:

  • 自定义功能
  • trim 可以完成 whereset 的功能

12.5 SQL片段

  • 将一些重复的sql提取出来,定义一个sql片段
<sql id="if-title-author">
    <if test="title != null">
        title = #{title},
    </if>
    <if test="author != null">
        author = #{author},
    </if>
    <if test="views != null">
        views = #{views},
    </if>
</sql>
<!--  更新  -->
<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <!--  引用 SQL片段  -->
        <include refid="if-title-author"/>
    </set>
    where id = #{id};
</update>

12.6 foreach

在这里插入图片描述

用法:

<select id="queryBlogForEach" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="authors" item="author" open="author in(" separator="," close=")">
            #{author}
        </foreach>
    </where>
</select>

测试:

//测试foreach
@Test
public void testForEach(){
    SqlSession sqlSession = MybatisUtils.getSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

    HashMap map = new HashMap();
    ArrayList<String> list = new ArrayList<String>();
    list.add("nych");
    list.add("nyc");
    list.add("nn");

    map.put("authors",list);

    List<Blog> blogs = blogMapper.queryBlogForEach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

如果authors为空的sql语句:

select * from blog

authors不为空的sql语句:

select * from blog WHERE author in( ? , ? , ? )

12.7 bind

  • 可以创建一个变量,来保存需要的内容
<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>

13. 缓存

13.1 简介

  • 查询时: 连接数据库,再查数据; 耗资源
  • 那么,将一次的查询结果,暂存到内存,我们再次查询相同数据时,直接走缓存; 提高效率

什么是缓存:

  • 存在内存的临时数据。

  • 将用户经常查询的数据放到缓存(内存)中,用户查询数据时就不需要再从数据库中查数据了,直接从缓存中查询,从而提高效率,解决高并发系统的性能问题

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

  • 经常查询不经常改变的数据,使用缓存

  • 经常修改的数据,不建议使用缓存

13.2 MyBatis缓存

  • MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。

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

    • 默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。
    • 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
    <cache/>
    

12.3 一级缓存

  • 一级缓存也叫本地缓存
  • 默认开启,在一个sqlSession中有效
@Test
public void test(){
    SqlSession sqlSession = MybatisUtils.getSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

	//两次查询同一个用户    
    User user1 = userMapper.getUserById(1);
    System.out.println("user1 = " + user1);

    System.out.println("-----------------------------------------");

    User user2 = userMapper.getUserById(1);
    System.out.println("user2 = " + user2);
	//引用是否相同
    System.out.println(user1 == user2);

    sqlSession.close();
}

连接一次数据库,执行一遍sql语句

第二次直接从缓存中获取

在这里插入图片描述

  • 所有 select 语句的结果将会被缓存。

  • 所有 insert、update 和 delete 语句会刷新缓存。

    在这里插入图片描述

  • 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。

  • 缓存不会定时进行刷新(也就是说,没有刷新间隔)。

  • 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。

  • 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。

手动清理缓存:

sqlSession.clearCache();

12.4 二级缓存

  • 二级缓存也叫全局缓存,作用域比一级缓存的高

  • 在一个namaspace中有效,一个命名空间,对应一个二级缓存

  • 工作方式

    • 一个会话查询一条数据后,数据会被放到当前会话的一级缓存中
    • 如果会话关闭了, 这个会话对应的一级缓存中的数据会被保存到二级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取数据
    • 不同的mapper查出的数据存放到自己对应的缓存中

要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:

<cache/>

这些属性可以通过 cache 元素的属性来修改。比如:

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>

**解释:**这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

清除策略:

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

默认的清除策略是 LRU

**flushInterval(刷新间隔):**属性可以被设置为任意的正整数,设置的值应该是一个以毫秒为单位的合理时间量。 默认情况是不设置,也就是没有刷新间隔,缓存仅仅会在调用语句时刷新。

**size(引用数目):**属性可以被设置为任意正整数,要注意欲缓存对象的大小和运行环境中可用的内存资源。默认值是 1024。

**readOnly(只读):**属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓存对象的相同实例。 因此这些对象不能被修改。这就提供了可观的性能提升。而可读写的缓存会(通过序列化)返回缓存对象的拷贝。 速度上会慢一些,但是更安全,因此默认值是 false。

提示: 二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新。

测试:

    @Test
    public void TestCache(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println("user = " + user);
        sqlSession.close();

        SqlSession sqlSession1 = MybatisUtils.getSession();
        UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = userMapper1.getUserById(1);
        System.out.println("user1 = " + user1);

        System.out.println(user == user1);
        sqlSession1.close();
    }

结果:

在这里插入图片描述

注意:

  • 如果开启二级缓存时,没有设置任何参数,实体类需要实现序列号接口(Serializable)

12.5 自定义缓存 ehcache

  • Ehcache 是一种广泛使用的开源Java分布式缓存,主要面向通用缓存
  1. 导包

    <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.2.1</version>
    </dependency>
    
  2. 配置

    <?xml version="1.0" encoding="UTF-8" ?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
            updateCheck="false">
    
    <diskStore path="./tmpdir/Tmp_EhCache"/>
    
    <defaultCache
    eternal="false"
    maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"
    />
    
    <cache
    name="cloud_user"
    eternal="false"
    maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"
    />
            
    

贝。 速度上会慢一些,但是更安全,因此默认值是 false。

提示: 二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新。

测试:

    @Test
    public void TestCache(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println("user = " + user);
        sqlSession.close();

        SqlSession sqlSession1 = MybatisUtils.getSession();
        UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = userMapper1.getUserById(1);
        System.out.println("user1 = " + user1);

        System.out.println(user == user1);
        sqlSession1.close();
    }

结果:

[外链图片转存中…(img-8nHMjJAJ-1627894514014)]

注意:

  • 如果开启二级缓存时,没有设置任何参数,实体类需要实现序列号接口(Serializable)

12.5 自定义缓存 ehcache

  • Ehcache 是一种广泛使用的开源Java分布式缓存,主要面向通用缓存
  1. 导包

    <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.2.1</version>
    </dependency>
    
  2. 配置

    <?xml version="1.0" encoding="UTF-8" ?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
            updateCheck="false">
    
    <diskStore path="./tmpdir/Tmp_EhCache"/>
    
    <defaultCache
    eternal="false"
    maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"
    />
    
    <cache
    name="cloud_user"
    eternal="false"
    maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"
    />
            
    

    ok


  • 3
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值