狂神说JAVA笔记:Mybatis

Mybatis

#{}和${}的区别是什么?
a、#{}是预编译处理,${}是字符串替换。
b、Mybatis 在处理#{}时,会将 sql 中的#{}替换为?号,调用 PreparedStatement 的 set 方法来赋值;
c、Mybatis 在处理${}时,就是把${}替换成变量的值。
d、使用#{}可以有效的防止 SQL 注入,提高系统安全性。
  1. 导入依赖

     <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.7</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
    
  2. 从 XML 中构建 SqlSessionFactory

    <?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>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <!--                5.7之后不要随意使用useSSL=true-->
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="UserMapper.xml"/>
        </mappers>
    </configuration>
    
    public class MybatisTool {
        private static SqlSessionFactory sqlSessionFactory;
        static {
            try{
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        public static SqlSession getSqlSession()
        {
            return sqlSessionFactory.openSession();
        }
    }
    
  3. 从 SqlSessionFactory 中获取 SqlSession

        SqlSession sqlSession = MybatisTool.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUsers();
        for (User user : users) {
            System.out.println(user);
        }

mybatis封装工具类

public class MybatisTool {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try{
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

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

这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。

SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。

SqlSession

每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。

1 CRUD

xml中namespace要和包名一致,id是方法名

    <select id="getUserById" parameterType="int" resultType="com.learn.entity.User">
        select * from mybatis.user where id=#{id}
    </select>
    public User getUserById(int id);
        SqlSession sqlSession = MybatisTool.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();

2 万能的MAP

Map传递参数,直接在sql中取出key即可!【parameterType=“map”】

对象传递参数,直接在sql中取对象的属性即可! 【parameterType=“Object”】

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

多个参数用Map,或者注解!

//接口
public int setUser(Map<String ,Object> map);
//xml配置
    <update id="setUser" parameterType="Map">
        update mybatis.user set name=#{myUser},pwd=#{myPwd} where id=#{myId}
    </update>
//调用
        HashMap<String, Object> map = new HashMap<>();
        map.put("myUser","didi");
        map.put("myPwd","didi");
        map.put("myId",3);
        SqlSession session = MybatisTool.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        int i = mapper.setUser(map);
        session.commit();
        session.close();

3 模糊查询

模糊查询怎么写?

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

List<User> userList = mapper.getuserLike("%李%");

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

select * from mybatis.user where name like "%"#{value}"%"

4 配置剖析

1. 核心配置文件mybatis-config.xml

2. 环境配置(environments)

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

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

学会使用配置多套运行环境!

Mybatis默认的事务管理器就是JDBC,连接池: POOLED

3. 属性(properties)

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

这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可通过properties元素的子元素来传递

driver=
url=
username=
password=

在mybatis-config.xml中引入(也可以增加配置)

mybatis-config.xml优先使用外部配置

4. 类型别名(typeAliaes)

在mybatis-config.xml中配置

第一种方式:设置一个缩写名字

<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <typeAlias alias="Blog" type="domain.blog.Blog"/>
  <typeAlias alias="Comment" type="domain.blog.Comment"/>
  <typeAlias alias="Post" type="domain.blog.Post"/>
  <typeAlias alias="Section" type="domain.blog.Section"/>
  <typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

第二种方式:会使用 Bean 的首字母小写的非限定类名来作为它的别名

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

第三种注解方式:别名为其注解值

@Alias("author")
public class Author {
    ...
}
别名     映射类型
_byte	byte
_long	long
_short	short
_int	int
_integer	int
_double	double
_float	float
_boolean	boolean
string	String
byte	Byte
long	Long
short	Short
int	Integer
integer	Integer
double	Double
float	Float
boolean	Boolean
date	Date
decimal	BigDecimal
bigdecimal	BigDecimal
object	Object
map	Map
hashmap	HashMap
list	List
arraylist	ArrayList
collection	Collection
iterator	Iterator

5. 设置(settings)

<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b6szIM89-1627046337369)(C:\Users\Henry\AppData\Roaming\Typora\typora-user-images\image-20210718163417403.png)]

6. 其他配置:

  • 类型处理器(typeHandlers)

  • 对象工厂(objectFactory)

  • 插件(plugins)

    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper

7. 映射器(mapper)

第一种

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>

第二种:

必须mapper.xml和类名同名,并且在同一个包下

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>

第三种:扫描包注入,必须同名,必须同包

<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

8. 生命周期和作用域

理解我们之前讨论过的不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder

这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。

SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。

SqlSession

每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。 下面的示例就是一个确保 SqlSession 关闭的标准模式:

try (SqlSession session = sqlSessionFactory.openSession()) {
  // 你的应用逻辑代码
}

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

id name  pwd   		数据库
id name  password   实体类

结果集映射

    <resultMap id="userMap" type="com.learn.entity.User">
<!--        <id column="id" property="id"/>-->
<!--        <result column="name" property="name"/>-->
        <result column="pwd" property="password"/>
    </resultMap>

    <select id="getUserById" parameterType="int" resultMap="userMap">
        select * from mybatis.user where id=#{id}
    </select>

6. 日志

日志工厂

setttings

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-quAOs0x4-1627046337372)(C:\Users\Henry\AppData\Roaming\Typora\typora-user-images\image-20210718201618238.png)]

  • log4j 掌握
  • studout_loggintg 掌握
logj4j:

导入依赖 : maven

properties配置 : log4j.properties

简单使用
static Logger logger = Logger.getLogger(类名.class);

7. 分页

1. 使用limit

select * from tabelname limit startIndex,pageSize;
 public List<User> usersLimit(Map<String,Integer> map);
    <resultMap id="userMap" type="com.learn.entity.User">
<!--        <id column="id" property="id"/>-->
<!--        <result column="name" property="name"/>-->
        <result column="pwd" property="password"/>
    </resultMap>
	<select id="usersLimit" parameterType="map" resultMap="userMap">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>

2.RowBounds分页

不使用sql实现

1接口

public List<User> usersRowBounds();

2.xml

        <resultMap id="userMap" type="com.learn.entity.User">
<!--        <id column="id" property="id"/>-->
<!--        <result column="name" property="name"/>-->
        <result column="pwd" property="password"/>
    </resultMap>

	<select id="usersRowBounds" resultMap="userMap">
        select * from mybatis.user
    </select>

3测试

    @Test
    public void rowBounds()
    {
        SqlSession session = MybatisTool.getSqlSession();
        RowBounds rowBounds = new RowBounds(1, 1);
        List<User> list = session.selectList("com.learn.Dao.UserMapper.usersRowBounds", null, rowBounds);
        for (User user : list) {
            System.out.println(user.toString());
        }
        session.close();
    }

3. 分页插件 PageHelper

了解

Mybatis执行流程

img

8. 注解开发

面向接口编程:

解耦: 定义与实现分离

使用注解开发:

CRUD

//可以设置自动提交事务
    public static SqlSession getSqlSession()
    {
        return sqlSessionFactory.openSession(true);
    }
    @Select("select * from user where id = #{id}")
    public User getUserById(@Param("id") int id);
@Param()注解
  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上!
  • 我们在SQL中引用的就是我们这里的@Param()中设定的属性名!

9. Lombok

Project Lombok 是一个 Java 库,可自动插入您的编辑器并构建工具,为您的 Java 增添趣味。

永远不要再编写另一个 getter 或 equals 方法,通过一个注释,您的类就有一个功能齐全的构建器,自动化您的日志变量等等。

从2020.3 版本开始,Jetbrains IntelliJ IDEA编辑器与 lombok 兼容,无需插件。

@Data 注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
@Setter :注解在属性上;为属性提供 setting 方法
@Setter :注解在属性上;为属性提供 getting 方法
@Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象
@NoArgsConstructor :注解在类上;为类提供一个无参的构造方法
@AllArgsConstructor :注解在类上;为类提供一个全参的构造方法
@Cleanup : 可以关闭流
@Builder : 被注解的类加个构造者模式
@Synchronized : 加个同步锁
@SneakyThrows : 等同于try/catch 捕获异常
@NonNull : 如果给参数加个这个注解 参数为null会抛出空指针异常
@Value : 注解和@Data类似,区别在于它会把所有成员变量默认定义为private final修饰,并且不会生成set方法。

测试环境搭建

导入lombok

新建实体类Teacher,Student建立Mapper接口

建立Mapper.XML文件

在核心配置文件中绑定注册我们的Mapper接口或者文件!

测试查询是否能够成功!

10. 多对一

​ association:处理对象

按照查询嵌套处理

    <select id="getStus" resultMap="st">
        select * from student
    </select>

    <resultMap id="st" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="Teacher" select="tSelect"/>
    </resultMap>
    <select id="tSelect" resultType="Teacher">
        select * from teacher where id=#{tid}
    </select>

按照结果嵌套处理

注意:教师id查不到

    <select id="getStuById" resultMap="SAT">
        select s.id sid, s.name sname, t.name tname from student s , teacher t where s.id = #{id} and s.tid=t.id;
    </select>
    <resultMap id="SAT" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

11、一对多

按照结果嵌套处理

    <select id="getStudentsByTeacherId" resultMap="teachers">
        select t.id tid,t.name tname,s.id sid,s.name sname from teacher t, student s where t.id=#{id} and s.tid=t.id;
    </select>
    <resultMap id="teachers" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

按照查询嵌套处理

    <select id="getStudentsByTeacherId2" resultMap="tstudents">
        select * from teacher where id=#{id};
    </select>
    <resultMap id="tstudents" type="Teacher">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="students" ofType="Student" javaType="ArrayList" select="qweq" column="id"/>
    </resultMap>
    <select id="qweq" resultType="Student">
        select * from student where tid=#{id}
    </select>

小结:

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

注意点:

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

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

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

  • from teacher where id=#{id};







    select * from student where tid=#{id}




### 小结:

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

### 注意点:

* 保证SQL的可读性,尽量保证通俗易懂
* 注意一对多和多对一中,属性名和字段的问题!
* 如果问题不好排查错误,可以使用日志,建议使用Log4j

##   12. 动态SQL

### if

```xml
    <select id="getByX" resultType="student" parameterType="map">
        select * from student where 1=1
        <if test="tid != null">
            and tid = #{tid}
        </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>

where

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>

set

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

trim

看看与 set 元素等价的自定义 trim 元素吧:

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

where 元素等价的自定义 trim 元素为

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

sql片段

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

1.使用SQL标签抽取公共的部分

2.在需要使用的地方使用Include标签引用即可

注意事项:

最好基于单表来定义SQL片段!

不要存在where标签

    <sql id="studentSelect">
        <if test="tid != null">
            and tid = #{tid}
        </if>
    </sql>

    <select id="getByX" resultType="student" parameterType="map">
        select * from student where 1=1
        <include refid="studentSelect"></include>
    </select>

foreach

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

    <select id="getStusByMap" parameterType="map" resultType="student">
        select * from student
        <where>
            <foreach collection="ids" item="id" index="1" open="(" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>

注释:index 是当前迭代的序号 意为: map中第几个集合

13. 缓存

简介

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

Mybatis缓存

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

一级缓存(默认开启)

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

一级缓存失效的情况:

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

二级缓存

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

二级缓存刷新:

  • 映射语句文件中的所有 select 语句的结果将会被缓存。

  • 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。

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

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

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

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

使用二级缓存步骤:

  1. 在mybatis-config.xml中显示的开启全局缓存

            <setting name="cacheEnable" value="true"/>
    
  2. 在mapper.xml中使用二级缓存

    <cache
      eviction="FIFO"
      flushInterval="60000"
      size="512"
      readOnly="true"/>
    
  3. 需要将实体类序列化,否则会报错

小结:

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

缓存顺序:

  1. 先看二级缓存有没有
  2. 再看一级缓存有没有
  3. 执行sql查询

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R956O3Mx-1627132192177)(C:\Users\Henry\AppData\Roaming\Typora\typora-user-images\image-20210724202940196.png)]

自定义缓存ehcache

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值