Mybatis学习笔记

第一个Mybatis程序

搭建环境

  1. 新建一个普通的maven项目
  2. 删除src目录
  3. 导入maven依赖
  <!--导入依赖-->
    <dependencies>
        <!--mysqp驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

创建一个模块

  • 编写mybatis的核心配置文件
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

</configuration>
  • 编写mybatis工具类
//SqlSessionFactory -->sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            //使用mybatis第一步:获取SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
    // 可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
    public static SqlSession getSqlSession(){
         return sqlSessionFactory.openSession();
    }

}

编写代码

  • 实体类
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接口
public interface UserDao {
    List<User> getUserList();
}

  • 接口实现类

    <?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.hjm.dao.UserDao">
        <select id="getUserList" resultType="com.hjm.pojo.User">
            select * from mybatis.user
        </select>
    </mapper>
    

测试

注意点:

​ org.apache.ibatis.binding.BindingException: Type interface com.hjm.dao.UserDao is not known to the MapperRegistry.

  • junit测试
{
    @Test
    public void test(){
        //1.0 获得sqlSession对象
         SqlSession sqlSession = MybatisUtils.getSqlSession();
         //2.0 执行sql
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //3.0 关闭sqlSession
        sqlSession.close();

    }
}

CRUD

select

选择,查询语句

  • id:就是namespace中的方法名
  • resultType:sql语句执行的返回值
  • parameterType:参数类型
  1. 编写接口
public interface UserMapper {
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);
    //插入一个用户
    int addUser(User user);
    //修改用户
    int updateUser(User user);
    //删除用户
    int deleteUser(int id);

}
  1. 编写对应的mapper.xml中的sql语句

    <mapper namespace="com.hjm.dao.UserMapper"> 
    
        <select id="getUserList" resultType="com.hjm.pojo.User">
            select * from mybatis.users
        </select>
        <select id="getUserById" resultType="com.hjm.pojo.User" parameterType="int">
            select * from mybatis.users where id = #{id}
        </select>
        <insert id="addUser" parameterType="com.hjm.pojo.User">
            insert into mybatis.users (id,name,pwd) values (#{id},#{name},#{pwd});
        </insert>
        <update id="updateUser" parameterType="com.hjm.pojo.User">
            update mybatis.users
            set name = #{name},pwd=#{pwd}
            where id=#{id};
        </update>
        <delete id="deleteUser" parameterType="com.hjm.pojo.User">
            delete from mybatis.users where id=#{id}
        </delete>
    </mapper>
    
  2. 测试

public class UserDaoTest {
    @Test
    public void test(){
        //1.0 获得sqlSession对象
         SqlSession sqlSession = MybatisUtils.getSqlSession();
         //2.0 执行sql
        UserMapper userDao = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //3.0 关闭sqlSession
        sqlSession.close();

    }
    @Test
    public void getUserByIdtest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(1);
        System.out.println(userById);
        sqlSession.close();
    }
    @Test
    public void addUserTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(4,"dasd","12314"));
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void updateUserTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(4,"zhfds","35465"));
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteUserTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }
}

注意:增删改需要提交事务

模糊查询

  1. java代码执行的时候,传递通配符% %

  2. 在sql拼接中使用通配符

万能的Map

假设,我们的实体类,或者数据库中的表,字段过多或参数过多,应当考虑使用Map

Map传递参数,直接在sql中取出key即可

对象传递参数,直接在sql中取出对象的属性即可

只有一个基本类型参数的情况下,可以直接在sql中取到

配置解析

1、 核心配置文件

  • mybatis-config.xml
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

2、环境配置

  • MyBatis 可以配置成适应多种环境
  • 尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
  • Mybatis默认的事务管理器是jdbc,连接池:POOLED

3、 属性(properties )

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

  • 这些属性可以在外部进行配置,并可以进行动态替换。既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。

  • 编写一个配置文件 db.properties

    driver=com.mysql.jdbc.Driver
    url=dbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
    username=root
    password=123456
    
  • 在核心配置文件中引入

<properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置

4、 类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。
  • 意在降低冗余的全限定类名书写
    <!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.hjm.pojo.User" alias="User"/>
    </typeAliases>
  • 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,扫描实体类的包,它的默认别名就是这个类的类名首字母小写
    <typeAliases>
        <package name="com.hjm.pojo"/>
    </typeAliases>
  • 在实体类比较少的时候,使用第一种;实体类比较多的时候,使用第二种

5、设置(settings)

6、 映射器

  • MapperRegistry:注册我们绑定的Mapper文件
  • 方式一:
    <mappers>
        <mapper resource="com/hjm/dao/UserMapper.xml"/>
    </mappers>
  • 方式二:使用class文件绑定注册
    <mappers>
        <mapper class="com.hjm.dao.UserMapper"/>
    </mappers>
  • 方式三:使用扫描包进行绑定
    <mappers>
        <package name="com.hjm.dao"/>
    </mappers>

7、生命周期和作用域

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

sqlSessionFactoryBuilder

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

sqlSessionFactory

  • 说白了就是数据库连接池
  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • SqlSessionFactory 的最佳作用域是应用作用域

sqlSession

  • 连接到连接池的一个请求
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 用完赶紧关闭,否则资源被占用

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

解决办法:

  • 起别名

resultMap

  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了

结果集映射

 <!--结果集映射--> 
<resultMap id="USerMap" type="USer">
        <!--colum代表数据库中的字段,property代表实体类中的属性-->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="psw" property="password"/>
    </resultMap>
    <select id="getUserList" resultMap="UserMap">
        select * from mybatis.users
    </select>

6、日志

日志工厂

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QMEvnVfB-1668926562005)(C:\Users\admin\Desktop\新建文件夹\捕获12.PNG)]

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

在Mybatis中具体使用哪一个日志,在设置中实现

log4j

  1. 导入log4j包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

  1. 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/hjm.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
  1. 配置log4j为日志的实现
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

简单使用

  1. 要在使用Log4j的类中,导入包import org.apache.log4j.Logger;
  2. 日志对象,参数为当前类的class
 static Logger logger = Logger.getLogger(UserDaoTest.class);

7、 分页

使用Limit分页

  1. 接口
List<User> getUserListByLImit(Map<String,Integer> map);
  1. Mapper.xml
    <select id="getUserListByLImit" parameterType="map" resultMap="UserMap">
        select * from mybatis.users limit #{startIndex},#{pageSize}
    </select>
  1. 测试
    public  void tsetgetUserListByLImit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> users = mapper.getUserListByLImit(map);
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();

    }

分页插件

pageHelper

8、使用注解开发

  1. 注解在接口上实现

    @Select("select * from users")
    List<User>  getUsers();
    
  2. 在核心配置文件中绑定接口

        <mappers>
            <mapper class="com.hjm.dao.UserMapper"/>
        </mappers>
    
  3. 测试

本质:反射机制实现

底层:动态代理

9、 Lombok

使用步骤:

  1. 在IDEA中安装Lombok插件

  2. 在项目中导入Lombok的jar包

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.10</version>
                <scope>provided</scope>
            </dependency>
    
    1. @Data:无参构造,get,set,tostring,hashcode,equals
    2. @AllArgsConstructor
    3. @NoArgsConstructor

10、多对一

测试环境搭建

  1. 导入Lombok
  2. 新建实体类Teacher,Student
  3. 建议Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定Mapper.xml文件
  6. 测试查询成功

按照查询嵌套处理

    <select id="getStudent" resultMap="studentTeacher" >
        select *from mybatis.student
    </select>
    <resultMap id="studentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="teacher">
        select *from mybatis.teacher where id=#{id}
    </select>

按照结果查询嵌套

    <select id="getStudent2" resultMap="studentTeacher2">
        select s.id sid,s.name sname,t.id tid, t.name tname
        from mybatis.student s,mybatis.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 property="id" column="tid"/>
        </association>
    </resultMap>

11、 一对多

按照结果嵌套处理

    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.id tid,t.name tname
        from mybatis.student s ,mybatis.teacher t
        where s.tid=t.id and t.id=#{tid}
    </select>
    <resultMap id="TeacherStudent" 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>

按照查询嵌套处理

 <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from mybatis.teacher where id=#{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudent" column="id"/>
    </resultMap>
    <select id="getStudent" resultType="Student">
        select * from mybatis.student where tid=#{tid}
    </select>

小结

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

12、 动态SQL

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

搭建环境

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT 博客id,
`title` VARCHAR(100) NOT NULL COMMENT 博客标题,
`author` VARCHAR(30) NOT NULL COMMENT 博客作者,
`create_time` DATETIME NOT NULL COMMENT 创建时间,
`views` INT(30) NOT NULL COMMENT 浏览量
)ENGINE=INNODB DEFAULT CHARSET=utf8

创建一个基础工程

  1. 导包

  2. 编写配置文件

  3. 编写实体类

    public class Blog {
        private int id;
        private  String title;
        private  String author;
        private Date createTime;
        private int views;
    }
    
  4. 编写实体类对应的Mapper接口和Mapper.xml文件

IF

    <select id="quarryBlogIf" 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>

where标签

    <select id="quarryBlogIf" 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>

set

    <update id="UpdateBlogSet" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author=#{author},
            </if>
        </set>
        where id=#{id}
    </update>

choose(when,otherwise)

    <select id="quarryBlogChoose" parameterType="map" resultType="Blog">
        select * from mybatis.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>

SQL片段

  1. 使用SQL标签抽取公共的部分
    <sql id="if-title">
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="views!=null">
            and views=#{views}
        </if>
    </sql>
  1. 在需要使用的地方用include标签引用即可

        <select id="quarryBlogIf" parameterType="map" resultType="blog">
            select *from mybatis.blog
            <where>
                <include refid="if-title"></include>
            </where>
        </select>
    

Foreach

    <select id="quarryBlogForEach" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <foreach collection="titles" item="title" open="and (" close=")" separator="or">
                title=#{title}
            </foreach>
        </where>
    </select>

缓存

简介

1、什么是缓存 [ Cache ]?

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

2、为什么使用缓存?

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

3、什么样的数据能使用缓存?

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

Mybatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。

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

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

一级缓存

一级缓存也叫本地缓存:

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

一级缓存失效的四种情况

一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;

一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!

1、sqlSession不同

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   SqlSession session2 = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session2.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper2.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
   session2.close();
}

观察结果:发现发送了两条SQL语句!

结论:每个sqlSession中的缓存相互独立

2、sqlSession相同,查询条件不同

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper2.queryUserById(2);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
}

观察结果:发现发送了两条SQL语句!很正常的理解

结论:当前缓存中,不存在这个数据

3、sqlSession相同,两次查询之间执行了增删改操作!

增加方法

//修改用户
int updateUser(Map map);

编写SQL

<update id="updateUser" parameterType="map">
  update user set name = #{name} where id = #{id}
</update>

测试

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);

   HashMap map = new HashMap();
   map.put("name","kuangshen");
   map.put("id",4);
   mapper.updateUser(map);

   User user2 = mapper.queryUserById(1);
   System.out.println(user2);

   System.out.println(user==user2);

   session.close();
}

观察结果:查询在中间执行了增删改操作后,重新执行了

结论:因为增删改操作可能会对当前数据产生影响

4、sqlSession相同,手动清除一级缓存

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);

   session.clearCache();//手动清除缓存

   User user2 = mapper.queryUserById(1);
   System.out.println(user2);

   System.out.println(user==user2);

   session.close();
}

一级缓存就是一个map

二级缓存

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

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

  • 工作机制

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

使用步骤

  • 1、开启全局缓存 【mybatis-config.xml】
<setting name="cacheEnabled" value="true"/>

​ 2、去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】

<cache/>

官方示例=====>查看官方文档
<cache
 eviction="FIFO"
 flushInterval="60000"
 size="512"
 readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

​ 3、代码测试

  • 所有的实体类先实现序列化接口
  • 测试代码
@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   SqlSession session2 = MybatisUtils.getSession();

   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session2.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   session.close();

   User user2 = mapper2.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session2.close();
}

结论

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据
  • 查出的数据都会被默认先放在一级缓存中
  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

Mybatis缓存原理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CyDfy5lO-1668926562007)(C:\Users\admin\Desktop\新建文件夹\缓存原理_20210927153202.png)]

自定义缓存-encache

Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;

要在应用程序中使用Ehcache,需要

  1. 引入依赖的jar包

  2. 在mapper.xml中使用对应的缓存即可

   <cache type = “org.mybatis.caches.ehcache.EhcacheCache” />
  1. 编写ehcache.xml文件,如果在加载时未找到/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="./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"/>
       <!--
          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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
      -->
    

sInMemory:缓存最大数目
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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
–>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值