Mybatis笔记 狂神说

本文档详细介绍了Mybatis的使用,从基础的环境搭建、CRUD操作,到Map和模糊查询,再到配置解析、日志、分页、注解开发、多对一和一对多处理、动态SQL及缓存机制。特别强调了Mybatis的配置文件、类型别名、日志配置以及分页插件的使用,并涵盖了错误处理和解决方案。
摘要由CSDN通过智能技术生成

1 什么是Mybatis

MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 JavaPOJOsPlain Ordinary Java Objects,普通的 Java对象)映射成数据库中的记录。

如何获得Mybatis?

  • maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>
  • Github:https://github.com/mybatis/mybatis-3/releases/tag/mybatis-3.5.2
  • 中文文档:https://mybatis.org/mybatis-3/zh/getting-started.html
  • 参考笔记:https://blog.csdn.net/li643937579/article/details/109194467

2 第一个Mybatis 程序

搭建环境→导入Mybatis→编写代码→测试!

2.1、搭建数据库

创建数据库和表

CREATE DATABASE `mybatis`;

USE `mybatis`;

CREATE TABLE `user`(
	`id` INT(20) NOT NULL PRIMARY KEY,
	`name` VARCHAR(30) DEFAULT NULL,
	`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`)VALUES
(1,'aaa','123456'),
(2,'bbb','123456'),
(3,'ccc','123456')
  1. 创建一个普通的Maven项目
  2. 删除src目录
  3. 导入依赖
    <!--  导入依赖  -->
     <dependencies>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.49</version>
         </dependency>
         <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
         <dependency>
             <groupId>org.mybatis</groupId>
             <artifactId>mybatis</artifactId>
             <version>3.5.2</version>
         </dependency>
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>4.13</version>
         </dependency>
     </dependencies>

2.2创建一个模块

  • 新建一个Module,普通的maven项目
  • 编写mybatis的核心配置文件

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"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.1.110:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="P17CKSzBp0q2@866"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
  • 编写mybatis工具类
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory; // 提升作用域
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 有了SqlSessionFactory,就可以从中获得SqlSession的实例了。
    // SqlSession 完全包含了面向数据库执行SQL命令所需的全部方法
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}
  • Dao接口
public interface UserDao {
    List<User> getUserList();
}
  • 接口实现类的UserDaoImpl转变为一个Mapper配置文件
<?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.meng.dao.UserDao">
    <!--  select查询语句  -->
    <select id="getUserList" resultType="com.meng.pojo.User">
        select * from mybatis.user
    </select>

</mapper>
  • 配置xml和properties过滤
<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

测试

我出现的问题:1. useSSL=fasle,2.<filtering>false</filtering>,3.UserMapper.xml的select的sql语句中不能有任何注释




3、CRUD

和select相同,只有sql语句要修改

id方法名
parameterTypesql输入
resultTypesql输出




4、Map和模糊查询

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

    // 万能的Map
    int addUser2(Map<String,Object> map);
    <!--  传递MapKey  -->
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user (id, pwd) values (#{userid},#{passWord});
    </insert>
    @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userid",5);
        map.put("passWord","222333");

        mapper.addUser2(map);

        sqlSession.commit();
        sqlSession.close();
    }

Map传递参数,直接在sql中取出key即可!【parameterType=“map”】
对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map,或者注解!


模糊查询

  1. Java代码执行的时候,传递通配符% %
    List<User> userList = mapper.getUserLike("%李%"); 会产生Sql注入的问题
    select * from mybatis.user where name like #{value}
  2. 在sql拼接中使用通配符
  3. List<User> userList = mapper.getUserLike("李"); 更安全
    select * from mybatis.user where name like "%"#{value}"%"



5、配置解析

1、核心配置文件

  • mybatis-config.xml
  • MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息。
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

2、环境配置(environments)

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

学会配置多套运行环境!
Mybatis默认的事务管理器就是JDBC,连接池:POOLED

3、属性(properties)

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

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

  1. 编写一个配置文件
    db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.110:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8
username=root
password=P17CKSzBp0q2@866
  1. 在核心配置文件中引入
<!--  引入外部配置文件  -->
    <properties resource="db.properties">
        <!--  这也可以写,但优先使用外部配置文件  -->
        <property name="username" value="root"/>
        <property name="password" value="P17CKSzBp0q2@866"/>
    </properties>

可以直接引入外部文件
可以在其中增加一些属性配置
如果两个文件有同一个字段,优先使用外部配置文件

4、类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。
  • 意在降低冗余的全限定类名书写。
    <!--  可以给实体类起别名  -->
    <typeAliases>
        <typeAlias type="com.meng.pojo.User" alias="User"/>
    </typeAliases>

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

<typeAliases>
  <package name="domain.blog"/>
</typeAliases>

在实体类较少的时候,使用第一种方式,可以DIY设置别名
如果实体类较多,建议使用第二种,不可以自定义别名

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

@Alias("author")
public class Author {
    ...
}

5、其他配置

typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)

6、映射器(mappers)

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

  • 方式一、【推荐使用】
<!--  每一个mapper.xml都需要在Mybatis核心配置文件中注册!  -->
     <mappers>
        <mapper resource="com/meng/dao/UserMapper.xml"/>
     </mappers>
  • 方式二、使用class文件绑定注册
<!--  每一个mapper.xml都需要在Mybatis核心配置文件中注册!  -->
     <mappers>
         <mapper class="com.meng.dao.UserMapper"/>
    5 </mappers>

注意点:

  1. 接口和他的Mapper配置文件必须同名!
  2. 接口和他的Mapper配置文件必须在同一个包下!
  • 方式三、使用扫描包进行注入绑定
<!--  每一个mapper.xml都需要在Mybatis核心配置文件中注册!  -->
     <mappers>
         <package name="com.meng.dao"/>
     </mappers>

8.生命周期(Scope)和作用域

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

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

SqlSessionFactory

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

SqlSession

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

请添加图片描述

这里的每一个Mapper,就代表一个具体的业务




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

当查询名与数据表的列名不同时,查出值为null

解决办法

  1. 起别名
    <select id="getUserById" parameterType="int" resultType="User">
        select id,name,pwd as password from mybatis.user where id = #{id}
    </select>
  1. resultMap结果集映射
    <resultMap id="UserMap" type="User">
        <!--    column数据库中的字段,property实体类中的属性    -->
        <!-- <result column="id" property="id"/>
        <result column="name" property="name"/> -->
        <result column="pwd" property="password"/>
    </resultMap>
    
    <!--  根据ID查询  -->
    <select id="getUserById" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>

resultMap 元素是 MyBatis 中最重要最强大的元素。
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。




7、日志

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

  • SLF4J
  • Apache Commons Logging
  • Log4j 2
  • Log4j
  • JDK logging

mybatis-config.xml

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

请添加图片描述

7.2、 Log4j

  1. 导包
<!-- 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/meng.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. 日志对象,



8、分页

分页可以减少数据的处理量

8.1 使用Mybatis实现分页,核心SQL

  1. 接口
// 分页
    List<User> getUserByLimit(Map<String,Integer> map);
  1. Mapper.xml
    <select id="getUserByLimit" parameterType="map" resultType="user">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>
  1. 测试
    @Test
    public void getUserByLimit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex",0);
        map.put("pageSize",2);

        List<User> userLimit = mapper.getUserByLimit(map);
        for (User user: userLimit){
            System.out.println(user);
        }
        sqlSession.close();
    }

8.2 RowBounds分页

  1. 接口
List<User> getUserByRowBounds();
  1. Mapper.xml
    <select id="getUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>
  1. 测试
    @Test
    public void getUserByRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        //RowBounds实现
        RowBounds rowBounds = new RowBounds(0, 2);

        //通过java代码层面实现分页
        List<User> userList = sqlSession.selectList("com.meng.dao.UserMapper.getUserByRowBounds",null,rowBounds);

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

        sqlSession.close();
    }

8.3 分页插件

有这个东西奥,真的。




9、使用注解开发

  1. 接口
    @Select("select * from user")
    List<User> getUsers();
  1. 需要在核心配置文件中绑定接口!
     <mappers>
         <mapper class="com.meng.dao.UserMapper"/>
     </mappers>
  1. 测试
    本质:反射机制
    底层:动态代理

请添加图片描述

Mybatis详细的执行流程!

9.1、 CURD

  1. 在MybatisUtils工具类创建的时候实现自动提交事务
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
  1. 编写接口,增加注释
public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();

    // 方法存在多个参数,所有参数前面必须加上@param("id")注解
    @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 = #{uid}")
    int deleteUser(@Param("uid") int id);
}
  1. 测试类
    【注意:必须要将接口注册绑定到核心配置文件中!】
 User user = mapper.getUserById(1);
 System.out.println(user);

 User user = new User(6, "mxc", "12345");
 mapper.addUser(user);

 User user = new User(6, "牛逼", "123432");
 mapper.updateUser(user);

 mapper.deleteUser(6);

9.2、@Param()注解

  • 基本类型的参数或者String类型需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型,可以不加,但建议加上
  • 在SQL中引用的是@Param("")中设定的属性名!
  • #{}${}相比,#{}有更高的安全性(防止SQL注入)



10、Lombok

使用步骤:

  1. 在IDEA中安装Lombok插件
  2. 在项目pom.xml文件中导入Lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
    <scope>provided</scope>
</dependency>
  1. 在实体类上加注解即可
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows

请添加图片描述




11、多对一处理

多个学生对应一个老师

按查询嵌套处理

    <!--
      思路:
          1.查询所有的学生信息
          2.根据查询出来的学生的tid,寻找对应的老师! 子查询-->
    <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 集合:collection      -->
        <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.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"/>
        </association>
    </resultMap>

回顾Mysql多对一查询方式:

  • 子查询
  • 联表查询



12、一对多处理

一个老师对应多个学生

按结果嵌套处理

    <select id="getTeacher" resultMap="TeacherToStudents">
        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="TeacherToStudents" 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="TeacherToStudents2">
        select * from teacher t where t.id = #{tid}
    </select>
    <resultMap id="TeacherToStudents2" type="Teacher">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="students" column="id" ofType="Student" select="getStudent"/>
    </resultMap>
    <select id="getStudent" resultType="Student">
        select * from student where tid = #{id}
    </select>

小结

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

面试高频

  1. Mysql引擎
  2. InnoDB底层原理
  3. 索引
  4. 索引优化



13、动态SQL

动态SQL是根据不同的条件生成不同的SQL语句
在SQL层面,去执行一个逻辑代码

搭建环境

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. 编写实体类
@Data
public class Blog {
    private int id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}
  1. 编写实体类对应Mapper接口和Mapper.xml文件

JSTL参考链接

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>
choose (when, otherwise)
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>
trim(where,set)
foreach
script
bind
多数据库支持
动态 SQL 中的插入脚本语言



14、缓存

Mybatis缓存

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

一级缓存

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

测试步骤:

  1. 开启日志
  2. 测试在一个Session中查询两次记录
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user1 = mapper.getUserById(1);
        System.out.println(user1.toString());

        System.out.println("====================");
        User user2 = mapper.getUserById(1);
        System.out.println(user1.toString());
        System.out.println(user1==user2);

        sqlSession.close();
    }
  1. 查看日志输出

请添加图片描述

缓存失效的情况

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

请添加图片描述

一级缓存默认开启,只在一次sqlSession中有效,也就是拿到链接关闭连接这个区间段!


二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果会话关闭了,这个会员对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取内容
    • 不同的mapper查询出的数据会放在自己对应的缓存(map)中

一级缓存开启(SqlSession级别的缓存,也称为本地缓存)

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

步骤:

  1. 开启全局缓存
在UserMapper.xml中添加
<cache/>
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
  1. 这些属性可以通过 cache 元素的属性来修改。
<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>

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

可用的清除策略有:

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

  1. 测试:需要将实体类序列化,否则就会报错 implements Serializable

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

缓存原理

请添加图片描述

注意:

  • 只有查询才有缓存,根据数据是否需要缓存(修改是否频繁选择是否开启)useCache=“true”
    <select id="getUserById" resultType="User" useCache="true">
        select * from mybatis.user where id = #{id}
    </select>

自定义缓存-ehcache

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

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

在Mapper中指定使用ehcache缓存实现

<cache-ref namespace="com.someone.application.data.SomeMapper"/>

=============================end







我遇到的错误

SqlSession空指针异常,是xml与接口映射有问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值