Java学习笔记10-2——MyBatis

(续上篇)

MyBatis详细执行流程

在这里插入图片描述

使用注解开发

简单的sql用注解,复杂的用xml

面向接口开发

  • 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向对象接口编程;
  • 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大角度遵守共同的标准,使的开发变得容易,规范性更好;
  • 在一个面向对象的而系统中,系统的各种功能是由许许多多的不同对象协作完成的。这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
  • 而各个对象之间的协作关系设计的关键。小到不同类之间的通信,大到各个模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解

  • 接口更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离
  • 接口本身反应了系统设计人员对系统的抽象管理。
  • 接口应有两类
    1.第一类是对一个个体的抽象,他可对应为一个抽象体(abstract class)
    2.第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface
  • 一个个体可能有多个抽象面,抽象体与抽象面是有区别的

三个面向区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现。
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的构架。

使用注解开发

注解在接口上实现:

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

    //方法存在多个参数,所有的参数必须加@Param
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

	// #{}里面的是实体类属性名
    @Insert("insert into user (id, name, pwd) values (#{id},#{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);

}

在核心配置文件中绑定接口:

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

对于增删改操作,如果要用注解实现,需要在MybatisUtil中改为自动提交事务:

public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }

测试:

public class UserMapperTest {
    @Test
    public void selectTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUsers();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void getByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);

        System.out.println(user);
        sqlSession.close();
    }

    @Test
    public void addTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(7, "asddfh","123"));
        sqlSession.close();
    }
    
    @Test
    public void updateTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(9, "zxczxc","123"));
        sqlSession.close();
    }
    
    @Test
    public void deleteTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(9);
        sqlSession.close();
    }
    
}

本质:反射机制实现
底层:动态代理
在这里插入图片描述

关于@Param( )注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
  • 我们在SQL中引用的就是我们这里的@Param()中设定的属性名

#{} 和 ${}

  • #{}是预编译处理,${}是字符串替换。
  • Mybatis 在处理#{}时,会将 sql 中的#{}替换为?号,调用 PreparedStatement 的 set 方法来赋值;
  • Mybatis 在处理${}时,就是把${}替换成变量的值。
  • 使用#{}可以有效的防止 SQL 注入,提高系统安全性。

复杂查询

property:映射到列结果的字段或属性。
column:数据库中的列名,或者是列的别名。

  • 多个学生关联一个老师(多对一)
  • 集合(一对多)

多对一问题

例:多个学生对应一个老师

多对一业务例子:
查询所有学生的信息,以及对应老师的信息

测试环境搭建

  1. 导入lombok(可选),建表
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, '秦老师');

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `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. 新建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private int id;
    private String name;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;

    //学生需要关联一个老师
    private Teacher teacher;
}
  1. 建立Mapper接口
public interface StudentMapper {
    List<Student> getStudent();
}
public interface TeacherMapper {
    @Select("select * from teacher where id = #{tid}")
    Teacher getTeacher(@Param("tid") int id);
}
  1. 建立Mapper.xml文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

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

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

<mapper namespace="com.cheng.dao.TeacherMapper">

</mapper>
  1. 在核心配置文件中绑定注册我们的Mapper接口或者文件
<mappers>
	<mapper resource="com/cheng/dao/TeacherMapper.xml"></mapper>
	<mapper resource="com/cheng/dao/StudentMapper.xml"></mapper>
</mappers>
  1. 测试
public class MyTest {
    @Test
    public void test1(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }
}

按照查询嵌套处理(子查询、嵌套查询)

StudentMapper.xml

<mapper namespace="com.cheng.dao.StudentMapper">
    <!--
         思路:
            1. 查询所有的学生信息
            2. 根据查询出来的学生的tid寻找特定的老师 (子查询)
        -->
    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>

    <resultMap id="StudentTeacher" type="com.cheng.pojo.Student">
        <result property="id" column="id"></result>
        <result property="name" column="name"/>
        <!--复杂的属性,我们需要单独出来
        对象:association
        集合:collection-->
        <!--javaType用于描述property的类型-->
        <association property="teacher" column="tid" javaType="com.cheng.pojo.Teacher" select="getTeacher">
        </association>
    </resultMap>

    <select id="getTeacher" resultType="com.cheng.pojo.Teacher">
        select * from teacher where id = #{id};
    </select>
</mapper>

测试

@Test
    public void test2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> student = mapper.getStudent();
        for (Student stuList : student) {
            System.out.println(stuList);
        }
        sqlSession.close();
    }

输出在这里插入图片描述

按照结果查询(联表查询、联合查询)

<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="com.cheng.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.cheng.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

回顾Mysql 多对一查询方式:

  • 子查询
  • 联表查询

一对多问题

例:一个老师有多个学生。对于老师而言为一对多。

一对多业务例子:
获取指定老师下的所有学生及老师的信息

环境搭建

  1. 重建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private int id;
    private String name;
    // 一个老师有多个学生
    private List<Student> student;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;
	// 学生关联一个老师
    private int tid;
}
  1. Mapper接口
public interface TeacherMapper {
    // 获取指定老师下的所有学生及老师的信息
    Teacher getTeacher(@Param("tid") int id);
}

按照结果查询(联表查询、联合查询)

TeacherMapper.xml

<mapper namespace="com.cheng.dao.TeacherMapper">

    <select id="getTeacher" 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="com.cheng.pojo.Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>

        <!--复杂的属性单独处理  javaType为指定属性的类型
        但对于集合中的泛型信息,我们用oftype获取-->
        <collection property="students" ofType="com.cheng.pojo.Student">
            <!--注意!!这里的collection的property的名称
            要和Teacher实体类的students属性名一致。
            ofType就是描述的是泛型里面的类型,因为要遍历List-->
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
</mapper>

测试

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

按照查询嵌套处理(子查询、嵌套查询)

(不推荐,较难理解)

Mapper.xml

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

    <resultMap id="TeacherStudent2" type="com.cheng.pojo.Teacher">
        <collection property="students" column="id" ofType="com.cheng.pojo.Student"
                    select="getStudentByTeacherId"></collection>
		<!--column="id"指的是将Teacher的id传给子查询-->
    </resultMap>

    <select id="getStudentByTeacherId" resultType="com.cheng.pojo.Student">
        select * from student where tid = #{tid}
    </select>

个人理解:
property=“students” column="id"这个结果集映射是指,执行完前面的SQL语句后,要将结果映射出Teacher类实体(sql执行完得到的数据赋给实体类对象),

但是Teacher类的List<Student> students属性无法跟数据库的teacher表的字段有映射关系(teacher表只有id和name俩字段,且都跟同名属性一一对应了),所以需要通过子查询赋予List<Student> students值,所以就要将这个属性property="students"暂时跟老师的id映射起来,传递给select=“getStudentByTeacherId”,

子查询getStudentByTeacherId得到Student类,将其赋给Teacher实体类的List<Student> students属性。

小结

  • 关联 - association 多对一
  • 集合 - collection 一对多
  • javaType & ofType
    JavaType用来指定实体中属性类型
    ofType映射到list中的类型,泛型中的约束类型

注意点:

  • 保证sql可读性,尽量保证通俗易懂
  • 注意字段问题
  • 如果问题不好排查错误,使用日志

面试高频:

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化

动态SQL

什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句

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

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

搭建环境

  1. 建表
create table `blog`(
	`id` varchar(80) 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 '浏览量',
    PRIMARY KEY (`id`)
	)ENGINE=InnoDB DEFAULT CHARSET=utf8
  1. 创建Maven项目,导包
  2. 创建实体类
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;
}
  1. Mapper接口
public interface BlogMapper {
    int addBlog(Blog blog);
}
  1. Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.cheng.dao.BlogMapper">
    <insert id="addBlog" parameterType="blog">
        insert into blog(id,title,author,create_time,views)values (#{id},#{title},#{author},#{createTime},#{views});
    </insert>
</mapper>
  1. 核心配置文件写好Mapper.xml映射

  2. 另外,因为实体类属性名和数据库表字段名不一致,核心配置文件开启驼峰命名和经典数据库字段命名规则自动映射

<!--是否开启驼峰命名和经典数据库字段命名规则映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
  1. 为了Blog的ID各不相同,编写一个生成随机ID的工具类
public class IdUtils {
    public static String getId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
  1. 添加数据
public class MyTest {
    @Test
    public void test() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        
        blog.setId(IdUtils.getId());
        blog.setTitle("Mybatis");
        blog.setAuthor("BUG质检员");
        blog.setCreateTime(new Date());
        blog.setViews(9999);
        mapper.addBlog(blog);

        blog.setId(IdUtils.getId());
        blog.setTitle("Java");
        mapper.addBlog(blog);

        blog.setId(IdUtils.getId());
        blog.setTitle("Spring");
        mapper.addBlog(blog);

        blog.setId(IdUtils.getId());
        blog.setTitle("微服务");
        mapper.addBlog(blog);

        // 记得设置自动提交事务
        sqlSession.close();
    }
}

动态SQL的常用语句

IF判断语句

  1. 接口
    // 查询博客
    List<Blog> queryBlogIf(Map map);
  1. Mapper.xml
    <!--使用where标签可以在当只查一个筛选条件时智能去掉and或or-->
<select id="queryBlogIf" parameterType="map" resultType="com.cheng.pojo.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);

        Map map = new HashMap();
        map.put("title", "java");
        List<Blog> list = blogMapper.queryBlogIf(map);
        for (Blog blog : list) {
            System.out.println(blog);
        }

        sqlSession.close();
    }

输出
在这里插入图片描述

choose-when-otherwise(单选语句)

类似Java中的switch
前面的满足就不管后面满不满足了,尽管后面的也满足,只会输出最前面满足的情况

    <!--提供了什么就按照什么来查找,啥都没提供就返回所有符合条件的-->
    <select id="queryBlogChoose" parameterType="map" resultType="com.cheng.pojo.Blog">
        select * from blog
        <where>
            <choose>
                <when test="title != null">
                    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);

        Map map = new HashMap();
        map.put("title", "java");
        map.put("views", "9999");
        List<Blog> list = blogMapper.queryBlogChoose(map);
        for (Blog blog : list) {
            System.out.println(blog);
        }

        sqlSession.close();
    }

在这里插入图片描述
可见即使后面views很多都满足值9999的条件的结果,但是不会输出

trim标签(连接SQL语句的前后缀标签。包括where标签和set标签,也可自定义标签)
where标签上面例子可以参考
set标签例子:

// 更新博客
    int updateBlog(Map map);
    <!--set标签类似where标签,都是最终跟SQL语句连起来的,跟where标签类似,会智能去掉逗号-->
    <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>
    @Test
    public void updateBlogTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Map map = new HashMap();
        map.put("title", "python");
        map.put("views", "1234");
        map.put("id","63caee93010b4f15ae3dbd676d73e7aa");
        mapper.updateBlog(map);

        sqlSession.close();
    }

自定义trim标签(了解即可,建议百度)

For-each遍历语句

例:遍历查询前三个id的博客(需要将前面例子的id的UUID改成1、2、3的id)
接口:

    // 遍历查询
    List<Blog> queryBlogForeach(Map map);

Mapper.xml:

    <!--select * from blog where (id=1 or id=2 or id=3)-->
    <!--使用map存放一个集合,ids是map的键,集合是键的值,集合里面装有id(Integer包装类)-->
    <!--ids是测试类传过来的,#{id}是遍历的-->
    <select id="queryBlogForeach" parameterType="map" resultType="com.cheng.pojo.Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="(" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>

测试类:

   @Test
    public void queryBlogForeachTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();

        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        map.put("ids",ids);// 要与xml中的<foreach collection的值同名

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

小结:
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
一般先在MySQL中写出完整的SQL,再对应的去修改成我们的动态SQL实现通用即可

SQL片段

有时我们会有一些经常重复且相同的代码,经常写重复的代码很烦

  • 使用SQL标签抽取公共部分
  • 在使用的地方使用include标签(有点像前端页面导入header和footer)

拿上面的queryBlogIf举例:


	<sql id="if-title-author">
	    <if test="title != null">
	        title = #{title}
	    </if>
	    <if test="author != null">
	        and author = #{author}
	    </if>
	</sql>

    <select id="queryBlogIf" parameterType="map" resultType="com.cheng.pojo.Blog">
        select * from blog
        <where>
			<include refid="if-title-author"></include>
        </where>
    </select>

注意:

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

Mybatis缓存

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

缓存简介

什么是缓存[Cache]?

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

为什么使用缓存?

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

什么样的数据可以使用缓存?

  • 经常查询并且不经常改变的数据 ,可以使用缓存
  • 不经常查询或者经常改变的数据,不建议使用缓存

MyBatis缓存

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

一级缓存

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

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

测试步骤:

  1. 开启日志

  2. 测试在一个Session中查询两次记录

  3. 查看日志输出

缓存失效的情况:

  • 查询不同的东西
  • 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
  • 查询不同的Mapper.xml
  • 手动清理缓存sqlSession.clearCache();

二级缓存

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

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

工作机制

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

测试步骤:

  1. 在核心配置文件中开启全局缓存
<!--显式地开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
  1. 在Mapper.xml中使用缓存
    这样使用默认配置
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>

这样使用自定义配置

<!--在当前Mapper.xml中使用二级缓存-->
<cache
       eviction="FIFO"
       flushInterval="60000"
       size="512"
       readOnly="true"/>

也可以单独设置某个查询是否使用缓存

<select id="getUserById" resultType="..." parameterType=".." useCache="true">

缓存策略

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

问题:我们需要将实体类序列化,否则就会报错
public class User implements Serializable{...}

小结:

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

缓存原理

在这里插入图片描述

自定义缓存 Ehcache

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

导入Maven

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>

在Mapper.xml中配置自定义缓存,设置成使用第三方自定义缓存

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值