Mybatis教程

MyBatis

​ MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。2013年11月迁移到Github

iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)。

​ MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。

Mybatis实现步骤

创建空项目 再创建Maven项目

  1. 新建数据库student表 id,name ,email,age四个字段的实体类,这里不再写出来
  2. 加入maven的mubatis坐标,mysql驱动的坐标
  3. 创建实体类,Student–保存表中的一行数据
  4. 创建持久层接口,定义操作数据库的方法
  5. 创建一个mybatis使用的配置文件 叫做sql映射文件:写sql语句的。一般一个表一个sql映射文件,这个文件是xml文件
    • 在接口所在的目录中。
    • 文件名称和接口保持一致
  6. 创建mybatis的主配置文件,一个项目就一个主配置文件。主配置文件提供了数据库的连接信息和sql映射文件的位置信息。
  7. 创建使用mybatis类,通过mybatis访问数据库

首先需要在maven项目添加mybatis和mysql驱动的依赖

<!--    mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
      <scope>compile</scope>
    </dependency>
<!--    mysql依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.25</version>
      <scope>compile</scope>
    </dependency>
<!--PageHelp依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>
<build>
    <!--插件编译的时候放到target目录里面--> 下面有讲述
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>

环境的部署

配置主配置文件
<?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>
    
     <!--settings:控制日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    
    <!--环境配置,数据库的连接信息-->
    <environments default="development">
        <!--enviroment:一个数据库信息的配置,环境
            id:一个唯一值,自定义,表示环境的名称
            default:告诉mybatis使用哪个数据库的连接信息,也就是访问哪个数据库
        -->
        <environment id="development">
            <!--
               transactionManager:mybatis的事务类型
               type:JDBC(表示使用JDBC中的Connection对象的commit,rollback做事务处理)
            -->
            <transactionManager type="JDBC"/>
            <!--
               dataSource:表示数据源,连接数据库的
               type:表示数据源的类型,POOLED表示使用连接池
            -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="ysh"/>
            </dataSource>
        </environment>
    </environments>
    <!--sql mapper (sql映射文件)的位置-->
    <mappers>
        <!--
            一个mapper标签指定一个文件的位置
            从类路径开始的路径信息,target/clasess(类路径)
         -->
        <mapper resource="com/ysh/dao/StudentDao.xml"/>
    </mappers>
</configuration>
<!--
      mybatis的主配置文件:主要定义了数据库的配置信息,sql映射文件的位置

      1.约束文件
        <!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
       mybatis-3-config.dtd:约束文件的名称
      2.<configuration>
-->
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">
<mapper namespace="com.ysh.dao.StudentDao">
    <!--
         select:表示查询操作。
         id:你要执行的sql语句语法的唯一标识,mybatis会使用这个id的值来查找到要执行的sql语句
             可以自定义,但是要求你使用接口中方法的名称
         resultType:表示结果类型的,是sql语句执行后得到ResultSet,遍历这个ResultSet得到java对象类型
                    值写的是类型的全限定名称
                    com.ysh.domain.Student是学生实体类的全限定名称
    -->
    <select id="selectStudents" resultType="com.ysh.domain.Student">
        select id,name ,email,age from student order by id
    </select>
</mapper>
<!--  sql映射文件:写sql语句的myvatis会执行这些sql
       1.指定约束文件
        <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        mybatis-3-mapper.dtd 是约束文件的名称,扩展名是dtd的。

       2.约束文件作用:限制,检查当前文件中出现的标签,属性必须符合mybatis的要求

       3.mapper 是当前文件的根标签,必须的。
         namespace:叫做命名空间,唯一值的,可以是自定义的字符串。
                    要求你使用dao接口的全限定名称
       4.在当前文件中,可以使用特定的标签,表示数据库的特定操作。
         <select>:表示执行查询,select语句
         <update>:表示更新数据库的操作,就是在<update>标签中 写的是update sql语句
         <insert>:表示插入,放的是insert语句
         <delete>:表示删除,执行的delete语句
-->

编译的时候会把配置文件拦截 在pom里面加入插件 这里我写道上面的依赖上

编写的测试类

package com.ysh;

import com.ysh.domain.Student;
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;
import java.util.List;

/**
 * @className: com.ysh.MyApp
 * @description: TODO
 * @author: YSH
 * @create: 2021-09-08 16:21
 */
public class MyApp {
    public static void main(String[] args) throws IOException {
        //访问mybatis读取student数据
        //1.定义mybatis主配置文件的名称,从类路径的根开始(target/clasess)
        String config="mybatis.xml";
        //2.读取这个config表示的文件
        InputStream in = Resources.getResourceAsStream(config);
        //3.创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4.创建SqlSessionFactory对象
        SqlSessionFactory factory = builder.build(in);
        //5.【重要】获取SqlSession对象 从SqlSessionFactory中获得SqlSession
        SqlSession sqlSession = factory.openSession();
        //6.【重要】指定要执行的sql语句的标识,sql映射文件中的namespace+“.”+标签的id值
        String sqlId="com.ysh.dao.StudentDao"+"."+"selectStudents";
        //7.执行sql语句通过sqlId找到语句
        List<Student> studentList = sqlSession.selectList(sqlId);
        //8.执行结果
        studentList.forEach(System.out::println);
        //9.关闭SqlSession对象
        sqlSession.close();

    }
}

下面我们插入一条数据

在StudentDao.xml文件加入sql语句

<select id="insertStudent">
        insert into student values (#{id},#{name},#{email},#{age})
    </select>

只有几步不一样 不重复写了

 //6.【重要】指定要执行的sql语句的标识,sql映射文件中的namespace+“.”+标签的id值
        String insertStu="com.ysh.dao.StudentDao"+"."+"insertStudent";

        //7.执行sql语句通过插入
        Student student=new Student(1212, "小王", "1561@qq.com",21);
        int result = sqlSession.insert(insertStu, student);
        //mybatis默认不是自动提交事务的,所以在insert,update,delete后要手工提交事务
        sqlSession.commit();
        //8.执行结果
        System.out.println("执行结果"+result);
        //9.关闭SqlSession对象
        sqlSession.close();

上面主配置文件加入日志后可以方便在控制台看到详细的信息

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

1 主要类的介绍
1) Resources: mybatis中的一个类, 负责读取主配置文件
InputStream in = Resources.getResourceAsStream(“mybatis.xml”);

2)SqlSessionFactoryBuilder : 创建SqlSessionFactory对象, 
     SqlSessionFactoryBuilder builder  = new SqlSessionFactoryBuilder();
    //创建SqlSessionFactory对象
    SqlSessionFactory factory = builder.build(in);

3)SqlSessionFactory : 重量级对象, 程序创建一个对象耗时比较长,使用资源比较多。
在整个项目中,有一个就够用了。

 SqlSessionFactory:接口  , 接口实现类: DefaultSqlSessionFactory
  SqlSessionFactory作用: 获取SqlSession对象。SqlSession sqlSession = factory.openSession();

  openSession()方法说明:
   1. openSession() :无参数的, 获取是非自动提交事务的SqlSession对象
	2. openSession(boolean): openSession(true)  获取自动提交事务的SqlSession. 
	                         openSession(false)  非自动提交事务的SqlSession对象

4)SqlSession:
SqlSession接口 :定义了操作数据的方法 例如 selectOne() ,selectList() ,insert(),update(), delete(), commit(), rollback()
SqlSession接口的实现类DefaultSqlSession。

使用要求: SqlSession对象不是线程安全的,需要在方法内部使用, 在执行sql语句之前,使用openSession()获取SqlSession对象。
在执行完sql语句后,需要关闭它,执行SqlSession.close(). 这样能保证他的使用是线程安全的。
封装的工具类
public class MyBatisUtils {
    private static SqlSessionFactory factory=null;
    static{
        String config ="mybatis.xml";
        try {
            InputStream in = Resources.getResourceAsStream(config);
            factory=new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static SqlSession getSqlSession(){
        SqlSession sqlSession=null;
        if(factory!=null){
            sqlSession=factory.openSession();
        }
        return sqlSession;
    }
}

这些都是我们写的实现dao层的接口,其实mybatis底层通过静态代理帮我们实现了只需要调用getmapper()方法就行了

 @Test
    public void TestSelectStudent_getMapper(){
        SqlSession sqlSession= MyBatisUtils.getSqlSession();
        StudentDao dao=sqlSession.getMapper(StudentDao.class);
        List<Student> students = dao.selectStudent();
        students.forEach(System.out::println);
    }

传入参数

传入参数: 从java代码中把数据传入到mapper文件的sql语句中。
1)parameterType : 写在mapper文件中的 一个属性。 表示dao接口中方法的参数的数据类型。
例如StudentDao接口
public Student selectStudentById(Integer id)

一个简单类型的参数:
简单类型: mybatis把java的基本数据类型和String都叫简单类型。
在mapper文件获取简单类型的一个参数的值,使用 #{任意字符}

 接口:public Student  selectStudentById(Integer id)
      mapper:select id,name, email,age from student where id=#{studentId}

传递多个参数

 <!--多个参数查询学生信息-->
    <select id="selectStudentParam" resultType="com.ysh.domain.Student">
        select id,name,email,age from student where name=#{myname} and age=#{myage}
    </select>
List<Student> selectStudentParam(@Param("myname") String name,@Param("myage") Integer age);

使用对象传递参数

public Student selectStudenyById(Student id);
<insert id="insertStudent">
        insert into student values (#{id},#{name},#{email},#{age})
</insert>

使用Map传递多个参数

​ Map 集合可以存储多个值,使用Map向 mapper 文件一次传入多个参数。Map 集合使用 String的 key, Object 类型的值存储参数。 mapper 文件使用 # { key } 引用参数值。

接口方法:

 List selectMultiMap(Map map); 

mapper 文件:

 select id,name,email,age from student where name=#{myname} or age =#{myage}

测试方法

Map<String,Object> data = new HashMap<>();
 data.put("myname","李力");// #{myname}
 data.put("myage",20); // #{myage}
 List<Student> stuList = studentDao.selectMultiMap(data);
 stuList.forEach( stu -> System.out.println(stu));

#和$

​ #:占位符,告诉 mybatis 使用实际的参数值代替。并使用 PrepareStatement 对象执行 sql 语句, #{…}代替 sql 语句的“?”。这样做更安全,更迅速,通常也是首选做法,

​ $ 字符串替换,告诉 mybatis 使用 包 含 的 “ 字 符 串 ” 替 换 所 在 位 置 。 使 用 S t a t e m e n t 把 s q l 语 句 和 包含的“字符串”替换所在位置。使用 Statement 把 sql 语句和 使Statementsql{}的 内容连接起来。主要用在替换表名,列名,不同列排序等操作。

mybatis的输出结果

1.mybayis执行了sql语句,得到的Java对象

1)resultType结果类型, 指sql语句执行完毕后, 数据转为的java对象, java类型是任意的。
resultType结果类型的它值 1. 类型的全限定名称 2. 类型的别名, 例如 java.lang.Integer别名是int

    处理方式:
	   1. mybatis执行sql语句, 然后mybatis调用类的无参数构造方法,创建对象。
		2. mybatis把ResultSet指定列值付给同名的属性。


		<select id="selectMultiPosition" resultType="com.bjpowernode.domain.Student">
      select id,name, email,age from student
    </select>

	  对等的jdbc
	  ResultSet rs = executeQuery(" select id,name, email,age from student" )
	  while(rs.next()){
           Student  student = new Student();
				student.setId(rs.getInt("id"));
				student.setName(rs.getString("name"))
	  }
  1. 定义自定义类型的别名
    1)在mybatis主配置文件中定义,使定义别名
    2)可以在resultType中使用自定义别名

    也可以使用注解自定义别名@Alias(“student”)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XNyBZYbD-1631324790761)(https://i.loli.net/2021/09/10/32EyX41eId5unZg.png)]

第二种方式

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

建议使用全限定名称,更安全。

resultMap

resultMap 可以自定义 sql 的结果和 java 对象属性的映射关系。更灵活的把列值赋值给指定属性。 常用在列名和 java 对象属性名不一样的情况。

使用方式:

​ 1.先定义 resultMap,指定列名和属性的对应关系。

​ 2.在中把 resultType 替换为 resultMap。

接口方法:
List<Student> selectUseResultMap(QueryParam param);
mapper 文件:
<!-- 创建 resultMap
 id:自定义的唯一名称,在<select>使用
 type:期望转为的 java 对象的全限定名称或别名 
-->
<resultMap id="studentMap" type="com.bjpowernode.domain.Student">
 <!-- 主键字段使用 id -->
 <id column="id" property="id" />
 <!--非主键字段使用 result-->
 <result column="name" property="name"/>
 <result column="email" property="email" />
 <result column="age" property="age" />
</resultMap>
<!--resultMap: resultMap 标签中的 id 属性值-->
<select id="selectUseResultMap" resultMap="studentMap">
 select id,name,email,age from student where name=#{queryName} or 
age=#{queryAge}
</select>

也可以使用列别名解决实体类和数据库字段名不一样

<select id="selectUseFieldAlias" 
resultType="com.bjpowernode.domain.PrimaryStudent">
 select id as stuId, name as stuName,age as stuAge
 from student where name=#{queryName} or age=#{queryAge}
</select>

模糊查询

模糊查询的实现有两种方式, 一是 java 代码中给查询数据加上“%” ; 二是在 mapper 文件 sql 语句的条件位置加上”%“

第一种方式,推荐使用第一种  
<select id="selectLikeFirst" resultType="com.bjpowernode.domain.Student">
 select id,name,email,age from student
 where name like #{studentName}
</select>
第二种方式只需要写参数不需要在字符串里面写%
<select id="selectLikeSecond" resultType="com.bjpowernode.domain.Student">
 select id,name,email,age from student
 where name like "%" #{studentName} "%"
</select>

动态sql

动态sql:sql的内容是变化的,可以根据条件取到不同的sql语句 主要是where部分发生变化

动态sql的实现,使用的是mybatis提供的标签, , ,

  1. < if> 是判断条件的,

    语法< if test=“判断Java对象的属性值”>

    ​ 部分sql语句

    ​ < /if>

    <select id="selectStudentIf" resultType="com.bjpowernode.domain.Student">
     select id,name,email,age from student
     where 1=1
     <if test="name != null and name !='' ">
         and name = #{name}
     </if>
     <if test="age > 0 ">
         and age &gt; #{age}
     </if>
    </select>
    
  • 用来包含 多个的, 当多个if有一个成立的, 会自动增加一个 where关键字,并去掉 if中多余的 and ,or等。

    <select id="selectStudentWhere" resultType="com.bjpowernode.domain.Student">
     select id,name,email,age from student
    <where>
     <if test="name != null and name !='' ">
         and name = #{name}
     </if>
     <if test="age > 0 ">
         and age &gt; #{age}
     </if>
     </where>
    </select>
    
    
  • < foreach> 循环

< foreach collection="" item="" open="" close="" separator="">
#{xxx}
< /foreach>

collection:表示接口中的方法参数的类型, 如果是数组使用array , 如果是list集合使用list
 item:自定义的,表示数组和集合成员的变量
 open:循环开始是的字符
 close:循环结束时的字符
separator:集合成员之间的分隔符

表达式中的 List 使用 list 表示,其大小使用 list.size 表示。 需求:查询学生 id 是 1002,1005,1006

接口方法: List selectStudentForList(List idList);

<select id="selectStudentForList" resultType="com.bjpowernode.domain.Student">
 select id,name,email,age from student
 <if test="list !=null and list.size > 0 ">
        where id in
          <foreach collection="list" open="(" close=")" item="stuid" separator=",">
             #{stuid}
          </foreach>
 </if>
</select>
@Test
public void testSelectForList() {
 List<Integer> list = new ArrayList<>();
 list.add(1002);
 list.add(1005);
 list.add(1006);
 List<Student> studentList = studentDao.selectStudentForList(list);
 studentList.forEach( stu -> System.out.println(stu));
}

参数是对象

接口方法: List selectStudentForList2(List stuList)

<select id="selectStudentForList2" 
resultType="com.bjpowernode.domain.Student">
 select id,name,email,age from student
   <if test="list !=null and list.size > 0 ">
            where id in
            <foreach collection="list" open="(" close=")" item="stuobject" separator=",">
                 #{stuobject.id}
             </foreach>
    </if>
</select>

自定义代码片段

sql代码片段, 就是复用一些语法
步骤
1.先定义 sql语句, 表名,字段等
2.再使用,

<sql id="studentSql">
 select id,name,email,age from student
</sql>
<select id="selectStudentSqlFragment" 
resultType="com.bjpowernode.domain.Student">
 <!-- 引用 sql 片段 -->
 <include refid="studentSql"/>
 <if test="list !=null and list.size > 0 ">
 where id in
 <foreach collection="list" open="(" close=")" 
item="stuobject" separator=",">
 #{stuobject.id}
 </foreach>
 </if>
</select>

数据库属性配置文件

  1. 数据库的属性配置文件: 把数据库连接信息放到一个单独的文件中。 和mybatis主配置文件分开。
    目的是便于修改,保存,处理多个数据库的信息。

    1)在resources目录中定义一个属性配置文件, xxxx.properties ,例如 jdbc.properties
    在属性配置文件中, 定义数据,格式是 key=value
    key: 一般使用 . 做多级目录的。
    例如 jdbc.mysql.driver , jdbc.driver, mydriver
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql//…
    jdbc.username=root
    jdbc.password=123456

    2)在mybatis的主配置文件,使用 指定文件的位置
    在需要使用值的地方, ${key}

主配置文件添加

<configuration>
    
    <!--指定properties文件的位置,从类的根路径开始找文件-->
    <properties resource="jdbc.properties"/>
<dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.passwd}"/>
            </dataSource>

放到resource目录下的数据库配置文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=ysh

2.mapper文件,使用package指定路径

    <!--第二种方式: 使用包名
        name: xml文件(mapper文件)所在的包名, 这个包中所有xml文件一次都能加载给mybatis
        使用package的要求:
         1. mapper文件名称需要和接口名称一样, 区分大小写的一样
         2. mapper文件和dao接口需要在同一目录
    -->
    <package name="com.bjpowernode.dao"/>
</mappers>

使用插件进行分页

先添加Pagehelp依赖

在主配置文件的环境的前面加入插件

 <!--配置插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
 /**
     * 测试查询学生信息(分页)
     */
    @Test
    public void TestselectStudenyPage(){
        SqlSession sqlSession= MyBatisUtils.getSqlSession();
        StudentDao dao=sqlSession.getMapper(StudentDao.class);
        //加入PageHelp的方法,分页
        //pageNum:第几页,从1开始
        //pageSize:一页中有多少个数据
        PageHelper.startPage(1,3);
        List<Student> students = dao.selectStudent();
        students.forEach(System.out::println);
    }

缓存

MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。 为了使它更加强大而且易于配置, MyBatis 3 中的缓存实现进行了许多改进。

默认情况下,只启用了本地的会话缓存(一级缓存),它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:

<cache/>  //写到mapper映射文件中 就会开启二级缓存

基本上就是这样。这个简单语句的效果如下:

  • 映射语句文件中的所有 select 语句的结果将会被缓存。
  • 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
  • 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
  • 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
  • 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
  • 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。

提示 缓存只作用于 cache 标签所在的映射文件中的语句。如果你混合使用 Java API 和 XML 映射文件,在共用接口中的语句将不会被默认缓存。你需要使用 @CacheNamespaceRef 注解指定缓存作用域。

首先在全局配置文件开启全局缓存

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

步骤:

  1. 开启全局缓存

    <!--显示的开启全局缓存-->
    <setting name="cacheEnabled" value="true"/> 
    
  2. 在要使用二级缓存的Mapper中开启

    <cache/>  //在当前的Mapper.xml中使用二级缓存
    

    也可以自定义参数

    <cache
      eviction="FIFO"         
      flushInterval="60000"  
      size="512"
      readOnly="true"/>
    

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

  3. 测试

    讲实体类序列化,否则会报错

cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
  1. 在要使用二级缓存的Mapper中开启

    <cache/>  //在当前的Mapper.xml中使用二级缓存
    

    也可以自定义参数

    <cache
      eviction="FIFO"         
      flushInterval="60000"  
      size="512"
      readOnly="true"/>
    

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

  2. 测试

    讲实体类序列化,否则会报错

cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值