Java MyBatis框架|更便捷的操作数据库(三)

狂神说Java Mybatis笔记
【狂神说Java】Mybatis最新完整教程IDEA版通俗易懂
GitHub源码项目:

10、复杂查询

10.1 测试环境搭建

10.1.1 新建表

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

在这里插入图片描述

10.1.2 新建类

  • 学生类
package com.kuang.pojo;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;

    //学生关联一个老师
    private Teacher teacher;
}
  • 老师类
package com.kuang.pojo;
import lombok.Data;

@Data
public class Teacher {
    private int id;
    private String name;
}
  • 新建Mapper
    在这里插入图片描述

10.1.3 测试

  • 配置
 <mappers>
	 <mapper class="com.kuang.dao.TeacherMapper"/>
	<mapper class="com.kuang.dao.StudentMapper"/>
</mappers>
  • 测试
package com.kuang.dao;

import com.kuang.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface TeacherMapper {
    @Select("select * from teacher where id = #{id}")
    Teacher getTeacher(@Param("id") int id);
}

	@Test
    public void getTeacherTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = teacherMapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }

在这里插入图片描述

10.2 多对一处理

SELECT * from student s,teacher t where s.tid = t.id;

在这里插入图片描述

10.2.1 按照查询嵌套处理(对象)

StudentMapper.java

List<Student> getStudent();
  • StudentMapper.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">

<mapper namespace="com.kuang.dao.StudentMapper">

    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>

    <resultMap id="StudentTeacher" type="student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂的属性,我们需要单独出来 对象:association 集合:collection-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
    </resultMap>

    <select id="getTeacher" resultType="Teacher">
        SELECT * from teacher
    </select>
<!--SELECT * from student s,teacher t where s.tid = t.id -->
</mapper>
  • 测试
	@Test
    public void getStudentTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = studentMapper.getStudent();
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }
  • 结果:
Student(id=1, name=小红, teacher=Teacher(id=1, name=青老师))
Student(id=2, name=小绿, teacher=Teacher(id=1, name=青老师))
Student(id=3, name=张三, teacher=Teacher(id=1, name=青老师))
Student(id=4, name=李四, teacher=Teacher(id=1, name=青老师))

10.2.3 按照查询嵌套处理(集合)

  • StudentMapper.xml
<!--
     思路:
        1. 查询所有的学生信息
        2. 根据查询出来的学生的tid寻找特定的老师 (子查询)
    -->
<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>
<resultMap id="StudentTeacher" type="student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--复杂的属性,我们需要单独出来 对象:association 集合:collection-->
    <collection property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="teacher">
    select * from teacher where id = #{id}
</select>

10.2.2 按照结果嵌套处理

StudentMapper.java

List<Student> getStudent2();
  • 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 property="name" column="sname"/>
        <association property="teacher" javaType="teacher">
            <result property="name" column="tname"></result>
        </association>
    </resultMap>

  • 测试
	@Test
    public void getStudentTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = studentMapper.getStudent2();
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }
  • 结果
Student(id=1, name=小红, teacher=Teacher(id=0, name=青老师))
Student(id=2, name=小绿, teacher=Teacher(id=0, name=青老师))
Student(id=3, name=张三, teacher=Teacher(id=0, name=青老师))
Student(id=4, name=李四, teacher=Teacher(id=0, name=青老师))

10.3 一对多处理

  • SQL
SELECT s.id sid, s.name sname,t.name tname,t.id tid FROM student s, teacher t
WHERE s.tid = t.id AND tid = 1

在这里插入图片描述

  • 实体类
package com.kuang.pojo;

import lombok.Data;

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

    //一个老师拥有多个学生
    private List<Student> students;
}
  • TeacherMapper.xml
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="StudentTeacher">
    SELECT s.id sid, s.name sname,t.name tname,t.id tid FROM student s, teacher t
    WHERE s.tid = t.id AND tid = #{tid}
</select>
<resultMap id="StudentTeacher" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--复杂的属性,我们需要单独处理 对象:association 集合:collection
    javaType=""指定属性的类型!
    集合中的泛型信息,我们使用ofType获取
    -->
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>
  • 测试
	@Test
    public void getTeacherTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = teacherMapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }
Teacher(id=1, name=青老师, students=[Student(id=1, name=小红, tid=1), Student(id=2, name=小绿, tid=1), Student(id=3, name=张三, tid=1), Student(id=4, name=李四, tid=1)])

10.4小结

  • 关联 - association 【多对一】

  • 集合 - collection 【一对多】

  • javaType & ofType
    JavaType用来指定实体类中的类型
    ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
    ​ 注意点:

  • 保证SQL的可读性,尽量保证通俗易懂

  • 注意一对多和多对一,属性名和字段的问题

  • 如果问题不好排查错误,可以使用日志,建议使用Log4j

  • 面试高频
    Mysql引擎
    InnoDB底层原理
    索引
    索引优化

11 、动态SQL

什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
所谓的动态SQL,本质上还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

11.1 搭建环境

CREATE TABLE `mybatis`.`blog`  (
  `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '博客id',
  `title` varchar(30) NOT NULL COMMENT '博客标题',
  `author` varchar(30) NOT NULL COMMENT '博客作者',
  `create_time` datetime(0) NOT NULL COMMENT '创建时间',
  `views` int(30) NOT NULL COMMENT '浏览量',
  PRIMARY KEY (`id`)
)
  1. 创建一个基础工程

  2. 导包

  3. 编写配置文件

  4. 编写实体类

@Data
public class Blog {
    private int id;
    private String title;
    private String author;

    private Date createTime;// 属性名和字段名不一致
    private int views;
}
  1. 编写实体类对应Mapper接口和Mapper.xml文件
  2. 配置
	<mappers>
        <mapper resource="com/kuang/dao/BlogMapper.xml"/>
    </mappers>
 <settings>
	<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

11.2 编写代码

  • 实体类
package com.kuang.pojo;

import lombok.Data;

import java.util.Date;


@Data
public class Blog {
    private String id;
    private String title;
    private String author;

    private Date createTime;// 属性名和字段名不一致
    private int views;

    public Blog(String id, String title, String author, Date createTime, int views) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.createTime = createTime;
        this.views = views;
    }
}

  • 工具类
package com.kuang.utils;

import org.junit.jupiter.api.Test;

import java.util.UUID;

@SuppressWarnings("all")
public class IdUtils {
    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    @Test
    public void test(){
        System.out.println(IdUtils.getId());
    }
}

  • BlogMapper.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">

<mapper namespace="com.kuang.dao.BlogMapper">
    <select id="addBlog" parameterType="blog"  resultType="Integer">
        insert into blog (id, title, author, createTime, views)
        value (#{id}, #{title}, #{author}, #{createTime}, #{views})
    </select>

</mapper>
  • 测试
package com.kuang.dao;

import com.kuang.pojo.Blog;
import com.kuang.utils.IdUtils;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;

public class BlogTest {
    @Test
    public void addBlogTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog(IdUtils.getId(), "good mybatis", "张三", new Date(), 10);
        int num = blogMapper.addBlog(blog);
        if (num > 0){
            System.out.println("插入成功");
        }
        sqlSession.close();
    }
}

在这里插入图片描述

11.3 if、where

(可匹配多个)
动态SQL
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

    List<Blog> queryBlogIf(Map map);
	<select id="queryBlogIf" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <if test="title!=null">
                and title = #{title}
            </if>
            <if test="author!=null">
                and author = #{author}
            </if>
        </where>
    </select>
  • 测试1
	@Test
    public void queryBlogIfTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

        HashMap map = new HashMap();
        List<Blog>  blogList = blogMapper.queryBlogIf(map);
        for (Blog blog : blogList) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
  • 测试2
Blog(id=c42c37ea73444383ac305627e2230a52, title=, author=张三, createTime=Sun Dec 05 10:01:19 CST 2021, views=10)
Blog(id=12fdff816f4243e492d8797048484e55, title=人民的名义, author=李四, createTime=Sun Dec 05 10:02:14 CST 2021, views=10)
Blog(id=a5578b9dad614857b4952b943a1164de, title=包青天, author=王五, createTime=Sun Dec 05 10:02:44 CST 2021, views=20)
	@Test
    public void queryBlogIfTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

        HashMap map = new HashMap();
        map.put("title","包青天");
        List<Blog>  blogList = blogMapper.queryBlogIf(map);
        for (Blog blog : blogList) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
Blog(id=a5578b9dad614857b4952b943a1164de, title=包青天, author=王五, createTime=Sun Dec 05 10:02:44 CST 2021, views=20)

11.4 choose (when, otherwise)

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句
(只匹配一个)

	<select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <choose>
                <when test="title!=null">
                    and title = #{title}
                </when>
                <when test="author!=null">
                    and author = #{author}
                </when>
                <otherwise>
                    and views = #{views}
                </otherwise>
            </choose>
        </where>
    </select>
	@Test
    public void queryBlogChooseTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

        HashMap map = new HashMap();
        map.put("views",10);
        List<Blog>  blogList = blogMapper.queryBlogChoose(map);
        for (Blog blog : blogList) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
==>  Preparing: select * from blog WHERE views = ? 
==> Parameters: 10(Integer)
<==    Columns: id, title, author, createTime, views
<==        Row: c42c37ea73444383ac305627e2230a52,, 张三, 2021-12-05 02:01:19, 10
<==        Row: 12fdff816f4243e492d8797048484e55, 人民的名义, 李四, 2021-12-05 02:02:14, 10
<==      Total: 2
Blog(id=c42c37ea73444383ac305627e2230a52, title=, author=张三, createTime=Sun Dec 05 10:01:19 CST 2021, views=10)
Blog(id=12fdff816f4243e492d8797048484e55, title=人民的名义, author=李四, createTime=Sun Dec 05 10:02:14 CST 2021, views=10)

11.5 trim、where、set

用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。

  <update id="updataBlogById"  parameterType="map">
        update mybatis.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>
 	@Test
    public void updataBlogTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

        HashMap map = new HashMap();
        map.put("id","c42c37ea73444383ac305627e2230a52");
        map.put("title","姐姐");
        int num = blogMapper.updataBlogById(map);
        if(num > 0){
            System.out.println("更新成功");
        }
        sqlSession.close();
    }
==>  Preparing: update mybatis.blog SET title = ? where id = ? 
==> Parameters: 姐姐(String), c42c37ea73444383ac305627e2230a52(String)
<==    Updates: 1
更新成功

11.6 foreach

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。

  • sql
select * from blog where 1=1 and (id = 1 or id = 2 or id = 3)

在这里插入图片描述

  • xml
<!--    select * from blog where 1=1 and (id = 1 or id = 2 or id = 3)-->
    <select id="queryForeach"   parameterType="map" resultType="blog">
        select * from blog where 1=1
        <foreach collection="idList" index="index" item="id"
            open="and (" separator="or" close=")">
                id = #{id}
        </foreach>
    </select>
	@Test
    public void queryForeachTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

        HashMap map = new HashMap();

        ArrayList<Integer> idList = new ArrayList<Integer>();
        idList.add(1);
        idList.add(3);
        map.put("idList",idList);

        List<Blog> blogList = blogMapper.queryForeach(map);
        for (Blog blog : blogList) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
==>  Preparing: select * from blog where 1=1 and ( id = ? or id = ? ) 
==> Parameters: 1(Integer), 3(Integer)
<==    Columns: id, title, author, createTime, views
<==        Row: 1, 姐姐, 张三, 2021-12-05 02:01:19, 10
<==        Row: 3, 包青天, 王五, 2021-12-05 02:02:44, 20
<==      Total: 2
Blog(id=1, title=姐姐, author=张三, createTime=Sun Dec 05 10:01:19 CST 2021, views=10)
Blog(id=3, title=包青天, author=王五, createTime=Sun Dec 05 10:02:44 CST 2021, views=20)

11.7 SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便服用!

  1. 定义SQL片段
<sql id="if-title-author">
    <if test="title!=null">
        title = #{title}
    </if>
    <if test="author!=null">
        and author = #{author}
    </if>
</sql>
  1. 使用SQL片段
    在需要使用的地方使用Include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <include refid="if-title-author"></include>
    </where>
</select>
==>  Preparing: select * from blog WHERE title = ? 
==> Parameters: 包青天(String)
<==    Columns: id, title, author, createTime, views
<==        Row: a5578b9dad614857b4952b943a1164de, 包青天, 王五, 2021-12-05 02:02:44, 20
<==      Total: 1
Blog(id=a5578b9dad614857b4952b943a1164de, title=包青天, author=王五, createTime=Sun Dec 05 10:02:44 CST 2021, views=20)

12、缓存

缓存

12.1 简介

解决高并发问题(读写)
读写分离,主从复制。

查询 : 连接数据库,耗资源
​ 一次查询的结果,给他暂存一个可以直接取到的地方 --> 内存:缓存
我们再次查询的相同数据的时候,直接走缓存,不走数据库了

  1. 什么是缓存[Cache]?
    • 存在内存中的临时数据
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
  2. 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销,提高系统效率
    • 什么样的数据可以使用缓存?
      经常查询并且不经常改变的数据 【可以使用缓存】

12.2 MyBatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存,缓存可以极大的提高查询效率。
  • MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
    • 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace(接口)级别的缓存。
      为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存

12.3 一级缓存(没啥用)

一级缓存也叫本地缓存:SqlSession

  • 与数据库同一次会话期间查询到的数据会放在本地缓存中
  • 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库

12.3.1 搭建环境

在这里插入图片描述

12.3.2 查询相同的东西

package com.kuang.dao;

import com.kuang.pojo.User;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {
    User getUserById(@Param("id") int id);
}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.kuang.dao.UserMapper">
    <select id="getUserById" resultType="user">
        select * from user where id = #{id}
    </select>
</mapper>

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 UserTest {
    @Test
    public void getUserByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = userMapper.getUserById(1);
        System.out.println(user);

        System.out.println("==============================");
        User user2 = userMapper.getUserById(1);
        System.out.println(user2);

        sqlSession.close();
    }
}
  • 同样的操作,sql 只执行了一次(缓存生效)
==>  Preparing: select * from user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 123
<==      Total: 1
User(id=1, name=张三, pwd=123)
==============================
User(id=1, name=张三, pwd=123)

12.3.3 查询不同的东西

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 UserTest {
    @Test
    public void getUserByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = userMapper.getUserById(1);
        System.out.println(user);

        System.out.println("==============================");
        User user2 = userMapper.getUserById(2);
        System.out.println(user2);

        sqlSession.close();
    }
}

  • 不同的操作,sql 执行了两次
==>  Preparing: select * from user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 123
<==      Total: 1
User(id=1, name=张三, pwd=123)
==============================
==>  Preparing: select * from user where id = ? 
==> Parameters: 2(Integer)
<==    Columns: id, name, pwd
<==        Row: 2, 干饭干饭, 1242
<==      Total: 1
User(id=2, name=干饭干饭, pwd=1242)

12.4 一级缓存失效的情况

  1. 查询不同的东西(12.3.3 查询不同的东西)
  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
  3. 查询不同的mapper.xml(此时二级缓存都失效,就别说一级缓存了)
  4. 手动清理缓存

12.4.1 增删改操作

可能会改变原来的数据,所以必定会刷新缓存

    int updataUserById(User user);
    <update id="updataUserById" parameterType="user">
        update user set name = #{name} , pwd = #{pwd} where id = #{id}
    </update>
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 UserTest {
    @Test
    public void getUserByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = userMapper.getUserById(1);
        System.out.println(user);

        System.out.println("==============================");
        int num = userMapper.updataUserById(new User(2,"张三","123"));
        if(num > 0){
            System.out.println("更新成功");
        }

        User user2 = userMapper.getUserById(1);
        System.out.println(user2);

        sqlSession.close();
    }
}

==>  Preparing: select * from user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 123
<==      Total: 1
User(id=1, name=张三, pwd=123)
==============================
==>  Preparing: update user set name = ? , pwd = ? where id = ? 
==> Parameters: 张三(String), 123(String), 2(Integer)
<==    Updates: 1
更新成功
==>  Preparing: select * from user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 123
<==      Total: 1
User(id=1, name=张三, pwd=123)
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@58695725]
Returned connection 1483298597 to pool.

进程已结束,退出代码为 0

12.4.2. 手动清理缓存

sqlSession.clearCache();
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 UserTest {
    @Test
    public void getUserByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = userMapper.getUserById(1);
        System.out.println(user);

        System.out.println("==============================");
        sqlSession.clearCache();
        System.out.println("手动清理缓存");

        User user2 = userMapper.getUserById(1);
        System.out.println(user2);

        sqlSession.close();
    }
}

==>  Preparing: select * from user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 123
<==      Total: 1
User(id=1, name=张三, pwd=123)
==============================
手动清理缓存
==>  Preparing: select * from user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 123
<==      Total: 1
User(id=1, name=张三, pwd=123)
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@bae7dc0]
Returned connection 195984832 to pool.

进程已结束,退出代码为 0

12.5 二级缓存

12.5.1 介绍

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存

  • 工作机制

    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果会话关闭了,这个会员对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取内容
    • 不同的mapper查询出的数据会放在自己对应的缓存(map)中
  • 一级缓存开启(SqlSession级别的缓存,也称为本地缓存)

  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。

12.6 开启全局缓存

步骤:

  1. mybatis-config.xml开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
  1. mapper.xml中使用缓存
<cache/>
<!--使用缓存-->
    <!--在当前Mapper.xml中使用二级缓存-->
    <cache
            eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>

    <select id="getUserById" resultType="user" useCache="true">
        select * from user where id = #{id}
    </select>

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

  • LRU – 最近最少使用:移除最长时间不被使用的对象。
  • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
  • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
  1. 测试
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 UserTest {
    @Test
    public void getUserByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        SqlSession sqlSession2 = MybatisUtils.getSqlSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();

        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = userMapper2.getUserById(1);
        System.out.println(user2);
        sqlSession2.close();
    }

}

==>  Preparing: select * from user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 123
<==      Total: 1
User(id=1, name=张三, pwd=123)
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2ed2d9cb]
Returned connection 785570251 to pool.
Cache Hit Ratio [com.kuang.dao.UserMapper]: 0.5
User(id=1, name=张三, pwd=123)

进程已结束,退出代码为 0

12.7 实现序列化接口

问题:我们需要将实体类序列化,否则未配置策略时会报错

org.apache.ibatis.cache.CacheException: Error serializing object.  Cause: java.io.NotSerializableException: com.kuang.pojo.User
  • 实现序列化接口
    com.kuang.pojo.User
package com.kuang.pojo;

import lombok.Data;

import java.io.Serializable;

@Data
public class User implements Serializable {
    private int id;
    private String name;
    private String pwd;

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
}

12.8 小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会放在一级缓存中
  • 只有当前会话提交,或者关闭的时候,才会提交到二级缓存中

一级缓存关闭,数据提交到二级缓存中

12.9 缓存原理

在这里插入图片描述

  • 测试
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 UserTest {
    @Test
    public void getUserByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        SqlSession sqlSession2 = MybatisUtils.getSqlSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();

        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = userMapper2.getUserById(1);
        System.out.println(user2);

        User user3 = userMapper2.getUserById(2);
        System.out.println(user3);

        sqlSession2.close();
    }
}

在这里插入图片描述

  • 注意:

只有查询才有缓存,根据数据是否需要缓存(修改是否频繁选择是否开启)

  • 设置需要缓存useCache=“true”
<select id="getUserById" resultType="user" useCache="true">
    select * from user where id = #{id}
</select>
  • 让增删改查不刷新缓存flushCache="false"
	<update id="updataUserById" parameterType="user" flushCache="false">
        update user set name = #{name} , pwd = #{pwd} where id = #{id}
    </update>

12.10 自定义缓存-ehcache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

  1. 导包
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>
  1. 在mapper中指定使用我们的ehcache缓存实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  1. 新建ehcache.xml
<?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:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
       user.home – 用户主目录
       user.dir  – 用户当前工作目录
       java.io.tmpdir – 默认临时文件路径
     -->
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
     -->
    <!--
      name:缓存名称。
      maxElementsInMemory:缓存最大数目
      maxElementsOnDisk:硬盘最大缓存个数。
      eternal:对象是否永久有效,一但设置了,timeout将不起作用。
      overflowToDisk:是否保存到磁盘,当系统当机时
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
      timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
      diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
      clearOnFlush:内存数量最大时是否清除。
      memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
      FIFO,first in first out,这个是大家最熟的,先进先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
      LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->
    <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"/>

</ehcache>
  1. MyCache
package com.kuang.utils;

import org.apache.ibatis.cache.Cache;

import java.util.concurrent.locks.ReadWriteLock;

public class MyCache implements Cache {
    @Override
    public ReadWriteLock getReadWriteLock() {
        return Cache.super.getReadWriteLock();
    }

    @Override
    public String getId() {
        return null;
    }

    @Override
    public void putObject(Object o, Object o1) {

    }

    @Override
    public Object getObject(Object o) {
        return null;
    }

    @Override
    public Object removeObject(Object o) {
        return null;
    }

    @Override
    public void clear() {

    }

    @Override
    public int getSize() {
        return 0;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值