MyBatis的缓存

项目文件截图:

MyBatis的缓存_第1张图片

一、缓存介绍

为什么使用缓存?

首次访问时,查询数据库,并将数据存储到内存中;再次访问时直接访问缓存,减少IO、硬盘读写次数、提高效率

Mybatis中的一级缓存和二级缓存?

1.一级缓存:

它指的是mybatis中的SqlSession对象的缓存。当我们执行完查询之后,查询的结果会同时存在在SqlSession为我们提供的一块区域中。当我们再次查询同样的数据,mybatis会先去SqlSession中查询是否有,有的话直接拿出来使用。当SqlSession对象消失时,Mybatis的一级缓存也就消失了。

2.二级缓存:

它指的是Mybatis中SqlSessionFactory对象的缓存,由同一个SqlSessioFactory对象创建的SqlSession共享其缓存。

MyBatis的缓存_第2张图片

二、一级缓存 

UserMapper代码:

public interface UserDao {
    //根据id查询用户信息
    public User findUserById(Integer id);
}

UserMapper.xml文件代码:




    

测试类代码:

package test;

import com.by.mapper.UserMapper;
import com.by.pojo.User;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class MyBatisFirstCacheTest {
    private SqlSession sqlSession;
    private InputStream inputStream;
    private SqlSessionFactory sessionFactory;

    @Before
    public void init() throws IOException {
        //加载mybatis-config.xml
        String resource = "mybatis-config.xml";
        inputStream = Resources.getResourceAsStream(resource);

        //创建sqlSessionFactory
        sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //创建sqlSession
        sqlSession = sessionFactory.openSession();
    }

    @Test
    public void testGoCache(){
        SqlSession sqlSession = sessionFactory.openSession();
        //拥有同一个sqlsession
        UserMapper userMapper1 = sqlSession.getMapper(UserMapper.class);
        UserMapper userMapper2 = sqlSession.getMapper(UserMapper.class);

        System.out.println("=============第一次查询============");
        User user1 = userMapper1.getUserById(41); //执行查询
        System.out.println(user1);

        System.out.println("=============第二次查询============");
        User user2 = userMapper2.getUserById(41);//执行查询?
        System.out.println(user2);
    }

    @Test
    public void testNoGoCache(){
        SqlSession sqlSession1 = sessionFactory.openSession();
        SqlSession sqlSession2 = sessionFactory.openSession();
        //拥有不同的sqlsession
        UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);

        System.out.println("=============第一次查询============");
        User user1 = userMapper1.getUserById(41); //执行查询
        System.out.println(user1);

        System.out.println("=============第二次查询============");
        User user2 = userMapper2.getUserById(41);//执行查询?不执行
        System.out.println(user2);
    }

    @Test
    public void testNoGoCache2(){
        SqlSession sqlSession = sessionFactory.openSession();
        //拥有同一个sqlsession
        UserMapper userMapper1 = sqlSession.getMapper(UserMapper.class);
        UserMapper userMapper2 = sqlSession.getMapper(UserMapper.class);

        System.out.println("=============第一次查询============");
        User user1 = userMapper1.getUserById(41); //执行查询
        System.out.println(user1);

        System.out.println("=============两次查询之间执行增删改=============");
        userMapper1.deleteUserById(1);
        sqlSession.commit();

        System.out.println("=============第二次查询============");
        User user2 = userMapper2.getUserById(41);//执行查询
        System.out.println(user2);
    }

    @After
    public void close() throws IOException {
       /* sqlSession.close();
        inputStream.close();*/
    }
}

 分析:

一级缓存是SqlSession范围的缓存,当调用SqlSession的commit(),close()等方法时,就会清空一级缓存。

MyBatis的缓存_第3张图片

  1. 第一次发起查询用户id为 1 的用户信息,先去找缓存中是否有id为 1 的用户信息,如果没有,从数据库查询用户信息。 得到用户信息,将用户信息存储到一级缓存中。

  2. 如果sqlSession去执行 commit操作(执行插入、更新、删除),清空 SqlSession 中的一级缓存,这样做的目的为了让缓存中存储的是最新的信息,避免脏读

  3. 第二次发起查询用户id为1的用户信息,先去找缓存中是否有id为1的用户信息,缓存中有,直接从缓存中获取用户信息。

 二级缓存:

UserMapper代码:

package com.by.mapper;

import com.by.pojo.User;

public interface UserMapper {
    User getUserById(Integer id);

    void deleteUserById(Integer id);
}

 UserMapper.xml文件代码:




    
    
    

    
        delete from mybatis.user where id=#{id}
    

 User类代码:

package com.by.pojo;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public void setId(Integer id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

 二级缓存测试类代码:

package test;

import com.by.mapper.UserMapper;
import com.by.pojo.User;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class MyBatisSecondCacheTest {
    private SqlSession sqlSession;
    private InputStream inputStream;
    private SqlSessionFactory sessionFactory;

    @Before
    public void init() throws IOException {
        //加载mybatis-config.xml
        String resource = "mybatis-config.xml";
        inputStream = Resources.getResourceAsStream(resource);

        //创建sqlSessionFactory
        sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //创建sqlSession
        sqlSession = sessionFactory.openSession();
    }

    @Test
    public void testGoCache(){
        SqlSession sqlSession1 = sessionFactory.openSession();
        SqlSession sqlSession2 = sessionFactory.openSession();
        //拥有相同的sqlSessionFactrory
        UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);

        System.out.println("=============第一次查询============");
        User user1 = userMapper1.getUserById(41); //执行sql
        System.out.println(user1);
        sqlSession1.commit(); //第一次查询session执行commit或close,才会把数据写到二级缓存

        System.out.println("=============第二次查询============");
        User user2 = userMapper2.getUserById(41);//执行sql?不执行sql
        System.out.println(user2);
    }

    @Test
    public void testNoGoCache() throws IOException {
        //加载mybatis-config.xml
        String resource = "mybatis-config.xml";

        InputStream inputStream1 = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory1 = new SqlSessionFactoryBuilder().build(inputStream1);

        InputStream inputStream2 = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory2 = new SqlSessionFactoryBuilder().build(inputStream2);

        SqlSession sqlSession1 = sessionFactory1.openSession();
        SqlSession sqlSession2 = sessionFactory2.openSession();
        //拥有不相同的sqlSessionFactrory
        UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);

        System.out.println("=============第一次查询============");
        User user1 = userMapper1.getUserById(41); //执行sql
        System.out.println(user1);
        sqlSession1.commit(); //第一次查询session执行commit或close,才会把数据写到二级缓存

        System.out.println("=============第二次查询============");
        User user2 = userMapper2.getUserById(41);//执行sql?执行sql
        System.out.println(user2);
    }

    @Test
    public void testNoGoCache2(){
        SqlSession sqlSession1 = sessionFactory.openSession();
        SqlSession sqlSession2 = sessionFactory.openSession();
        //拥有相同的sqlSessionFactrory
        UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);

        System.out.println("=============第一次查询============");
        User user1 = userMapper1.getUserById(41); //执行sql
        System.out.println(user1);
        sqlSession1.commit(); //第一次查询session执行commit或close,才会把数据写到二级缓存


        System.out.println("=============两次查询之间执行增删改查=============");
        userMapper1.deleteUserById(1);
        sqlSession1.commit();

        System.out.println("=============第二次查询============");
        User user2 = userMapper2.getUserById(41);//执行sql?执行sql
        System.out.println(user2);
    }

    @After
    public void close() throws IOException {
       /* sqlSession.close();
        inputStream.close();*/
    }
}

分析:

二级缓存是mapper映射级别的缓存,多个SqlSession去操作同一个Mapper映射的sql语句,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的。

二级缓存结构图:

MyBatis的缓存_第4张图片

你可能感兴趣的:(MyBatis,缓存)