Mybatis缓存详解

什么是Mybatis缓存?

  使用缓存可以减少Java Application与数据库的交互次数,从而提升程序的运行效率。比如,查询id=1的user对象,第一次查询出来之后,会自动将该对象保存到缓存中。下一次查询该对象时,就可以直接从缓存中获取,不需要发送SQL查询数据库了。

  Mybatis缓存分类

  一级缓存:SqlSession级别,默认开启,且不能关闭。

  mybatis的一级缓存是SqlSession级别的缓存,在操作数据库时需要构造SqlSession对象,在对象中有一个HashMap用于存储缓存数据,不同的SqlSession之间缓存数据区域(HashMap)是互相不影响的。

  一级缓存的作用域是SqlSession范围的,当在同一个SqlSession中执行两次相同的sql语句时,第一次执行完毕会将数据库中查询的数据写到缓存(内存)中,第二次查询时会从缓存中获取数据,不再去底层进行数据库查询,从而提高了查询效率。需要注意的是:如果SqlSession执行了DML操作(insert、update、delete),并执行commit()操作,mybatis则会清空SqlSession中的一级缓存,这样做的目的是为了保证缓存数据中存储的是最新的信息,避免出现脏读现象。

  当一个SqlSession结束后该SqlSession中的一级缓存也就不存在了,Mybatis默认开启一级缓存,不需要进行任何配置。

  二级缓存:Mapper级别,默认关闭,可以开启。

  二级缓存是Mapper级别的缓存,使用二级缓存时,多个SqlSession使用同一个Mapper的sql语句去操作数据库,得到的数据会存在二级缓存区域,它同样是使用HashMap进行数据存储,相比一级缓存SqlSession,二级缓存的范围更大,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的。

  二级缓存是多个SqlSession共享的,其作用域是mapper的同一个namespace,不同的SqlSession两次执行相同的namespace下的sql语句,且向sql中传递的参数也相同,即最终执行相同的sql语句,则第一次执行完毕会将数据库中查询的数据写到缓存(内存),第二次查询时会从缓存中获取数据,不再去底层数据库查询,从而提高查询效率。

  Mybatis默认关闭二级缓存,可以在setting全局参数中配置开启二级缓存。

  下面我们通过代码来学习如何使用MyBatis缓存。

  首先来演示一级缓存,以查询Student对象为例。

/**

  * @ClassName Student

  * @Description

  * @Author lzq

  * @Date 2019/7/26 13:53

  * @Version 1.0

  **/

  public class Student {

  private int SID;

  private String Sname;

  private String Ssex;

  private int Age;

  public int getSID() {

  return SID;

  }

  public void setSID(int SID) {

  this.SID=SID;

}

公共字符串getSname () {

返回Sname;

}

公共空setSname(字符串Sname) {

Sname=Sname;

}

公共字符串getSsex () {

返回Ssex;

}

公共空setSsex(字符串Ssex) {

Ssex=Ssex;

}

公共int getAge () {

返回年龄;

}

公共空setAge (int年龄){

=年龄;年龄

}

@Override

公共字符串toString () {

返回“[id“+ SID +名”字“+ Sname +”性别“+ Ssex +”年龄”+年龄+“]”;

}

}

StudentMapper接口:

进口org.apache.ibatis.annotations。*;

公共接口StudentMapper {

公共学生getStudentById (int id),

}

mybatis-config。xml:

公共”——//mybatis.org//DTD配置3.0//EN "

" http://mybatis.org/dtd/mybatis-3-config.dtd "在

StudentMapper。xml:

  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  select * from student where SID=#{id}

  测试代码:

  **

  * @ClassName Test

  * @Description

  * @Author lzq

  * @Date 2019/7/26 13:53

  * @Version 1.0

  **/

  public class Test {

  public static void main(String[] args) throws IOException {

  String resource="mybatis-config.xml";

//读取配置文件

  InputStream asStream=Resources.getResourceAsStream(resource);

//创建sqlSessionFactory

  SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(asStream);

//创建sqlSession

  SqlSession sqlSession=sqlSessionFactory.openSession();

//通过动态代理产生StudentMapper对象

  StudentMapper mapper=sqlSession.getMapper(StudentMapper.class);

//查询id为1的元组

Mybatis缓存详解