MyBatis缓存机制流程分析

news2024/10/5 16:23:34

前言

在进行分析之前,建议快速浏览之前写的理解MyBatis原理、思想,这样更容易阅读、理解本篇内容。

验证一级缓存

MyBatis的缓存有两级,一级缓存默认开启,二级缓存需要手动开启。

重复读取跑缓存

可以看到,第二次请求的时候,没有打印SQL,而是使用了缓存。

@Test
public void test1() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
    SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
    SysRoleMapper mapper1 = sqlSession1.getMapper(SysRoleMapper.class);
    SysRole role = mapper1.getById(2);
    SysRole role2 = mapper1.getById(2);
    System.out.println(role);
    System.out.println(role2);
}

//------------------------------打印SQL--------------------------------------

==>  Preparing: select * from sys_role where role_id = ?
==> Parameters: 2(Integer)
<==    Columns: role_id, role_name, role_key, role_sort, data_scope, status, del_flag, create_by, create_time, update_by, update_time, remark
<==        Row: 2, 测试2, common, 2, 2, 0, 0, admin, 2022-08-29 15:58:05, , null, 普通角色
<==      Total: 1
SysRole{role_id=2, role_name='测试2'}


SysRole{role_id=2, role_name='测试2'}

同一会话的更新操作刷新缓存

通过测试结果可以看到,因为更新操作的原因,两次查询都查了数据库。

@Test
public void test2() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
    SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
    SysRoleMapper mapper1 = sqlSession1.getMapper(SysRoleMapper.class);
    SysRole role = mapper1.getById(2);
    mapper1.updateRoleNameById("测", 2);
    SysRole role2 = mapper1.getById(2);
    System.out.println(role);
    System.out.println(role2);
}


//------------------------------打印SQL--------------------------------------


==>  Preparing: select * from sys_role where role_id = ?
==> Parameters: 2(Integer)
<==    Columns: role_id, role_name, role_key, role_sort, data_scope, status, del_flag, create_by, create_time, update_by, update_time, remark
<==        Row: 2, 测试2, common, 2, 2, 0, 0, admin, 2022-08-29 15:58:05, , null, 普通角色
<==      Total: 1


==>  Preparing: update sys_role set role_name = ? where role_id = ?
==> Parameters:(String), 2(Integer)
<==    Updates: 1


==>  Preparing: select * from sys_role where role_id = ?
==> Parameters: 2(Integer)
<==    Columns: role_id, role_name, role_key, role_sort, data_scope, status, del_flag, create_by, create_time, update_by, update_time, remark
<==        Row: 2,, common, 2, 2, 0, 0, admin, 2022-08-29 15:58:05, , null, 普通角色
<==      Total: 1


SysRole{role_id=2, role_name='测试2'}
SysRole{role_id=2, role_name='测'}

跨会话更新数据没有刷新缓存

@Test
public void test() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
    // 会话一
    System.out.println("会话一");
    SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
    SysRoleMapper mapper1 = sqlSession1.getMapper(SysRoleMapper.class);
    SysRole role = mapper1.getById(2);
    System.out.println(role);
    
    // 会话二
    System.out.println("会话二");
    SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
    SysRoleMapper mapper2 = sqlSession2.getMapper(SysRoleMapper.class);
    mapper2.updateRoleNameById("测试2", 2);
    System.out.println(mapper2.getById(2));
    
    // 会话一重新查询
    System.out.println("会话一重新查询");
    role = mapper1.getById(2);
    System.out.println(role);

}


//------------------------------打印结果--------------------------------------


会话一
SysRole{role_id=2, role_name='测试'}
会话二
SysRole{role_id=2, role_name='测试2'}
会话一重新查询
SysRole{role_id=2, role_name='测试'}

源码分析的入口点

我们要阅读、分析源码,就需要先找准一个切入点,我们以下面代码为例子,SysRoleMapper#getById()方法作为调试入口:

@Test
public void test1() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
    SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
    SysRoleMapper mapper1 = sqlSession1.getMapper(SysRoleMapper.class);
	// 调试入口
    SysRole role = mapper1.getById(2);
    SysRole role2 = mapper1.getById(2);
    System.out.println(role);
    System.out.println(role2);
}

在分析之前,我们就先约定一下:👉符号表示你的视角要焦距在哪几行代码。


一级缓存流程分析

好,现在我们开始分析一级缓存的流程,了解其设计思想,看看能学到什么。

MapperProxy

  • 首先,我们可以看到,通过getMapper方法拿到的对象mapper1,其实是一个代理对象MapperProxy的实例。

image.png

  • MapperProxy实现了InvocationHandler接口,所以SysRoleMapper调用的 方法 都会进入代理对象MapperProxyinvoke方法。
public class MapperProxy<T> implements InvocationHandler, Serializable {
    // 略

    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            // 先拿到声明method方法的类(在这里具体指定是SysRoleMapper)。
            // 如果是 Object 类,则表明调用的是一些通用方法,比如 toString()、hashCode() 等,就直接调用即可。
    👉👉👉if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            } else {
                return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
            }
        } catch (Throwable t) {
            throw ExceptionUtil.unwrapThrowable(t);
        }
    }


    // 略

}

小结:从上面可以知道,我们调用SysRoleMapper接口中的 方法,其实都会进入MapperProxy#invoke方法中。


现在,我们进一步看,由于getById方法不是Object默认的方法,所以会跑else分支,详情分析请看代码:

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else {// 跑else分支
        // 整体了解此行代码的流程:
        // 1.首先Method会被包装成MapperMethod;1️⃣
        // 2.MapperMethod被封装到PlainMethodInvoker类内;2️⃣
        // 3.此类(PlainMethodInvoke)提供一个普通的方法invoke,此方法会实际调用MapperMethod的execute方法3️⃣
👉👉👉return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }



private MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
    try {
      return MapUtil.computeIfAbsent(methodCache, method, m -> {
        // 是否Java语言规范定义的默认方法?否
        if (m.isDefault()) {
            // 这里的细节不要深究了
          try {
            if (privateLookupInMethod == null) {
              return new DefaultMethodInvoker(getMethodHandleJava8(method));
            } else {
              return new DefaultMethodInvoker(getMethodHandleJava9(method));
            }
          } catch (IllegalAccessException | InstantiationException | InvocationTargetException
              | NoSuchMethodException e) {
            throw new RuntimeException(e);
          }
        } else { // 看这里,跑的是else分支
          // 对于普通的方法(如SysRoleMapper#getById),使用的是PlainMethodInvoker实现类。
          // >>    其中,MapperMethod表示对原始的Method方法对象进行了一次包装(细节就先不深究了)
          // >>    mapperInterface 信息在创建MapperProxy对象的时候写入,信息默认来源于我们定义的mybatis-config.xml文件, 包括sqlSession也是。
          return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration())1️⃣);
        }
      });
    } catch (RuntimeException re) {
      Throwable cause = re.getCause();
      throw cause == null ? re : cause;
    }
  }


  private static class PlainMethodInvoker implements MapperMethodInvoker {
    private final MapperMethod mapperMethod;

    public PlainMethodInvoker(MapperMethod mapperMethod) {
      super();
      this.mapperMethod = mapperMethod;2️⃣
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
      return mapperMethod.execute(sqlSession, args);3️⃣
    }
  }

从上面注释中,相信你已经了解到MapperProxy#invoke方法下一步会流向哪个类:MapperMethod#execute()

MapperMethod

现在我们看看MapperMethod#execute()做了什么:根据command属性提供的sql方法类型调用sqlSession接口中合适的的处理方法。

public class MapperMethod {

    // 方法对应的sql类型:select、update、delete、insert
    // 在MapperProxy#invoke#cachedInvoker方法中创建MapperMethod类时设置的,感兴趣的可以回看
    private final SqlCommand command; 
    private final MethodSignature method;

    public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
        this.command = new SqlCommand(config, mapperInterface, method);
        this.method = new MethodSignature(config, mapperInterface, method);
    }

    // 这个方法整体做了什么?根据command提供的sql方法类型调用sqlSession接口中合适的的处理方法。
    // >>    我们之前封装MapperMethod的时候,定义了此类的command、method属性;
    // >>    其中command这个属性表示sql方法的类型
👉👉public Object execute(SqlSession sqlSession, Object[] args) {
        Object result;

    	// getById方法是查询语句,所以会进入SELECT分支
        switch (command.getType()) {
            case INSERT: {
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(sqlSession.insert(command.getName(), param));
                break;
            }
            case UPDATE: {
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(sqlSession.update(command.getName(), param));
                break;
            }
            case DELETE: {
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(sqlSession.delete(command.getName(), param));
                break;
            }
            case SELECT:
                if (method.returnsVoid() && method.hasResultHandler()) { // 无返回值,同时有专门的结果处理类
                    executeWithResultHandler(sqlSession, args);
                    result = null;
                } else if (method.returnsMany()) {  // 返回多个结果
                    result = executeForMany(sqlSession, args);
                } else if (method.returnsMap()) { // 返回map类型的结果
                    result = executeForMap(sqlSession, args);
                } else if (method.returnsCursor()) { // 返回结果是数据库游标类型
                    result = executeForCursor(sqlSession, args);
                } else { // 看这里,跑的是else分支:
                    // 获取参数对象,不用关注细节
                    Object param = method.convertArgsToSqlCommandParam(args);
                    // SysRoleMapper#getById结果类型是单个对象,所以最终跑的是这行代码
                👉👉result = sqlSession.selectOne(command.getName(), param);
                    // 下面代码细节不重要,就不展开了
                    if (method.returnsOptional()
                        && (result == null || !method.getReturnType().equals(result.getClass()))) {
                        result = Optional.ofNullable(result);
                    }
                }
                break;
            case FLUSH:
                result = sqlSession.flushStatements();
                break;
            default:
                throw new BindingException("Unknown execution method for: " + command.getName());
        }
        if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
            throw new BindingException("Mapper method '" + command.getName()
                                       + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
        }
        return result;
    }

    // 略

}

好了,看完上面代码,相信你已经知道下一步代码会跑到那里了:SqlSession#selectOne()

SqlSession是一个接口,定义了一些列通用的SQL操作,如selectList、insert、update、commit 和 rollback等操作。

小结:通过上面的分析,我们已经知道,我们调用SysRoleMapper#getById方法本质上其实还是调用SqlSession接口提供的通用SQL操作方法。只不过利用 代理 Mapper接口 的方式,实现方法调用 自动路由到SqlSession接口对应的方法。


SqlSession

通过上面分析,想必你已经知道下一步要走哪了,SqlSession接口默认的实现类是DefaultSqlSession,所以selectOne方法跑的是这个实现类:

public class DefaultSqlSession implements SqlSession {

    // 略

    @Override
    public <T> T selectOne(String statement, Object parameter) {
        // Popular vote was to return null on 0 results and throw exception on too many.(译:大众投票是在 0 个结果上返回 null,并在太多结果上抛出异常。)
        
        // 很明显,selectOne最终跑的是selectList方法
        List<T> list = this.selectList(statement, parameter);
        
        // 下面代码不用关注
        if (list.size() == 1) {
            return list.get(0);
        } else if (list.size() > 1) {
            throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
        } else {
            return null;
        }
    }

    // 略


    /**
       * 封装MappedStatement对象,通过executor发起查询。
       * @param statement 映射信息,方法的全路径:cn.lsj.seckill.SysRoleMapper.getById
       * @param parameter SQL参数
       * @param rowBounds 辅助分页,默认不分页。RowBounds(int offset, int limit)
       * @param handler 处理结果回调。查询完成之后调用回调
       * @return
       * @param <E>
       */
    private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
        try {
            // 这个类主要封装了SysRoleMapper相关信息,包括:方法全路径(id)、原始xml文件(resource)、
            // sql语句相关信息(sqlSource)、结果类型映射信息、与映射语句关联的缓存配置信息(cache)等
            MappedStatement ms = configuration.getMappedStatement(statement);
            
            // wrapCollection是懒加载机制的一部分,不用关注细节
    👉👉👉return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }

}

通过上述代码可以知道,selectOne方法内部最终还是依靠Executor接口的query方法去执行具体的sql,只不过在此之前会从Configuration配置类里面通过 映射信息 statement 拿到MappedStatement封装对象,然后传递给query方法。


Executor

在上面,我们了解到下一步走的是Executor接口的query方法,CachingExecutorExecutor接口的实现类,基于装饰者模式Executor功能进行了增强:增加了缓存机制。

public class CachingExecutor implements Executor {

    private final Executor delegate; // 默认被装饰的实现类 SimpleExecutor

    private final TransactionalCacheManager tcm = new TransactionalCacheManager();

    public CachingExecutor(Executor delegate) {
        this.delegate = delegate;
        delegate.setExecutorWrapper(this);
    }

    // 略


    @Override
    public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
        // 表示一条 SQL 语句以及相关参数(不用关注细节)
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        // 构造缓存的KEY(不用关注细节)
        CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
        return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
    }

    @Override
    public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
    throws SQLException {
        // 读取二级缓存的缓存对象
        Cache cache = ms.getCache();
        // 开启二级缓存时跑这个分支,先不关注
        if (cache != null) {
            flushCacheIfRequired(ms);
            if (ms.isUseCache() && resultHandler == null) {
                ensureNoOutParams(ms, boundSql);
                @SuppressWarnings("unchecked")
                List<E> list = (List<E>) tcm.getObject(cache, key);
                if (list == null) {
                    list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
                    tcm.putObject(cache, key, list); // issue #578 and #116
                }
                return list;
            }
        }
        // 通过断点可以看到:默认被装饰的Executor接口实现类是SimpleExecutor (图1️⃣)
        // 由于SimpleExecutor继承了抽象类BaseExecutor 但没有实现query方法,所以,最终指向的还是BaseExecutor#query() (图2️⃣)
👉👉👉return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
    }

    // 略

}

  • 图1️⃣

过断点查看delegate属性可知:默认被装饰的Executor接口实现类是SimpleExecutor

  • 图2️⃣

SimpleExecutor继承了抽象类BaseExecutor但没有实现query方法


通过上面代码注释,我们最终了解到CachingExecutor#query方法跑向的是BaseExecutor#query

现在,我们看一下BaseExecutor类的query方法:


public abstract class BaseExecutor implements Executor {

    // 略
    
    protected PerpetualCache localCache; // 缓存Cache(一级缓存)具体的一个实现类
    
    // 略

    @Override
    public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
        ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
        if (closed) {
            throw new ExecutorException("Executor was closed.");
        }
        if (queryStack == 0 && ms.isFlushCacheRequired()) {
            clearLocalCache();
        }
        // 很明显,这个是存储查询结果的,我们围绕这个对象来看代码
        List<E> list;
        try {
            queryStack++;
            // 从缓存中读取结果(第一次查询没有缓存)
            list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
            if (list != null) {
                handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
            } else { // 跑else分支
                // 从数据库中读取
        👉👉👉list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
            }
        } finally {
            queryStack--;
        }
        if (queryStack == 0) {
            for (DeferredLoad deferredLoad : deferredLoads) {
                deferredLoad.load();
            }
            // issue #601
            deferredLoads.clear();
            if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
                // issue #482
                clearLocalCache();
            }
        }
        return list;
    }

    // 略


    private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
        List<E> list;
        // 给key对应的缓存值设置一个占位值(只是用于占位)
        localCache.putObject(key, EXECUTION_PLACEHOLDER);
        try {
            // 真正处理查询的方法
            // 抽象类没有实现doQuery方法,所以方法的调用是其实现类 SimpleExecutor#doQuery
    👉👉👉list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
        } finally {
            localCache.removeObject(key);
        }
        localCache.putObject(key, list);
        if (ms.getStatementType() == StatementType.CALLABLE) {
            localOutputParameterCache.putObject(key, parameter);
        }
        return list;
    }
}

StatementHandler

RoutingStatementHandler

现在,我们在看看SimpleExecutor#doQuery方法,没有太多复杂逻辑,直接是交由StatementHandler接口处理了,接口的实现类是RoutingStatementHandler

在划分上,StatementHandler属于Executor的一部分,参与SQL处理:

  • RoutingStatementHandler :根据执行的 SQL 语句的类型(SELECT、UPDATE、DELETE 等)选择不同的 StatementHandler 实现进行处理。
  • PreparedStatementHandler :处理预编译 SQL 语句的实现类。预编译 SQL 语句是指在数据库预先编译 SQL 语句并生成执行计划,然后在后续的执行中,只需要传递参数并执行编译好的执行计划,可以提高 SQL 的执行效率。
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
        Configuration configuration = ms.getConfiguration();
        // 此接口用于处理数据库的 Statement 对象的创建和执行
        StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
        stmt = prepareStatement(handler, ms.getStatementLog());
👉👉👉return handler.query(stmt, resultHandler); // 打断点可以看到handler实现类:RoutingStatementHandler,它作用就是选择合适的StatementHandler实现类执行SQL
    } finally {
        closeStatement(stmt);
    }
}

我们再看看RoutingStatementHandler#query方法,使用了装饰者模式,被装饰类是PreparedStatementHandler
image.png

PreparedStatementHandler

RoutingStatementHandler选择了合适的处理类来执行SQL:PreparedStatementHandler

现在打开看看PreparedStatementHandler#query方法:

  @Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    // Java JDBC 中的一个接口,用于执行预编译的 SQL 语句。使用过JDBC编程的应该见过,可以看文末的JDBC编程Demo回忆回忆。
    PreparedStatement ps = (PreparedStatement) statement;
    // 执行 SQL 语句。
    ps.execute();
    // “结果处理器”会处理并返回查询结果(在这里就不深究了)
    return resultSetHandler.handleResultSets(ps);
  }

现在,让我们往回看BaseExecutor#queryFromDatabase方法:

  private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    // 给key对应的缓存值设置一个占位值(只是用于占位)
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
        // 此时,我们已经拿到结果了
   👉👉list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      localCache.removeObject(key);
    }
    // 将结果写入到缓存中 
    localCache.putObject(key, list);
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }

到这里,我们经历了一次(第一次)查询的过程,并在BaseExecutor#queryFromDatabase方法中,将查询结果写入到localCache属性中。

我们再查一次,就会发现,在BaseExecutor#query中,这次直接拿到了缓存的数据:

@Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    // 略
    List<E> list;
    try {
      queryStack++;
       // 从本地缓存拿到了上次的查询结果
 👉👉👉list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    // 略
    return list;
  }

小结

整个流程下来,发现最关键的地方就是BaseExecutor抽象类的queryqueryFromDatabase这两个方法,它们在一级缓存方面,围绕localCache属性做缓存操作。

  • 第一次查询,跑queryFromDatabase方法,并将查询结果写入localCache属性;
  • 第二次相同的查询,直接从localCache属性中读取缓存的查询结果。

二级缓存流程分析

开启二级缓存

添加配置到mybatis-config.xml文件:

<settings>
  <!-- 二级缓存-->
  <setting name="cacheEnabled" value="true"/>
</settings>

修改SysRoleMapper.xml文件:

<?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="cn.lsj.seckill.SysRoleMapper">

	<!-- 表示此namespace开启二级缓存 -->
  <cache/>

  <select id="getById" resultType="cn.lsj.seckill.SysRole" >
    select * from sys_role where role_id = #{id}
  </select>
  
</mapper>

流程分析

当我们开启二级缓存之后,查询过程就变成:二级缓存->一级缓存->数据库

二级缓存的验证代码:


  @Test
  public void test1() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
    SysRoleMapper mapper1 = sqlSession1.getMapper(SysRoleMapper.class);
    SysRole role = mapper1.getById(2);
    System.out.println(role);

    // 提交事务二级缓存数据才生效
    sqlSession1.commit();


    SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
    SysRoleMapper mapper2 = sqlSession2.getMapper(SysRoleMapper.class);
    SysRole role2 = mapper2.getById(2);
    System.out.println(role2);

    System.out.println(mapper1.getById(2));

  }

在前面的CachingExecutor#query方法中,我们看到了二级缓存的代码:

    @Override
    public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
    throws SQLException {
        Cache cache = ms.getCache();
        // 假如我们开启了二级缓存,那么我们的查询会先跑此分支
        if (cache != null) {
            flushCacheIfRequired(ms);
            if (ms.isUseCache() && resultHandler == null) {
                ensureNoOutParams(ms, boundSql);
                @SuppressWarnings("unchecked")
                // 从缓存中读取数据
        👉👉👉 List<E> list = (List<E>) tcm.getObject(cache, key);
                // 二级缓存中没有数据时再查数据库
                if (list == null) {
                    list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
                    // 将查询结果写入到二级缓存中
                    tcm.putObject(cache, key, list); // issue #578 and #116
                }
                return list;
            }
        }
		return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
    }

总结

看到这里,我们回顾一下,在之前的分析中,我们看到装饰者模式出现得比较频繁;此外还是用到动态代理技术。

整个分析下来,相信你收获的不止这些,源码阅读能力应该能得到一些提升,对设计模式、动态代理的理解也会有一些加深。

好了,如果你感兴趣的话,可以进一步深入分析缓存如何刷新、生效,如何做到缓存会话级别、Mapper级别的隔离的。

最后,留下一些思考问题:

  • 开启二级缓存之后,为什么sqlSession1.commit();之后二级缓存才生效?

附:JDBC编程Demo

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCDemo {
    public static void main(String[] args) {
        // MySQL服务器的JDBC URL、用户名和密码
        String url = "jdbc:mysql://localhost:3306/你的数据库名";
        String user = "你的用户名";
        String password = "你的密码";

        try {
            // 加载JDBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            Connection connection = DriverManager.getConnection(url, user, password);

            // 创建SQL语句
            String sql = "SELECT * FROM 你的表名";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 执行查询
            ResultSet resultSet = preparedStatement.executeQuery();

            // 处理结果集
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String email = resultSet.getString("email");

                System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
            }

            // 关闭资源
            resultSet.close();
            preparedStatement.close();
            connection.close();

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1303854.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ubuntu install sqlmap

refer: https://github.com/sqlmapproject/sqlmap 安装sqlmap&#xff0c;可以直接使用git 克隆整个sqlmap项目&#xff1a; git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev 2.然后进入sqlmap-dev&#xff0c;使用命令&#xff1a; python s…

利差是什么?anzo Capital昂首资本换个角度学利差

在交易论坛上最常问也是问的最多的一个问题就是“外汇中的利差是多少?”&#xff0c;今天让anzo Capital昂首资本换个角度试着找出答案。 在现代生活中&#xff0c;我们必须为商品和服务付费&#xff0c;包括金融市场上提供的商品和服务。同样的在金融市场中也需要为商品和服…

庙算兵棋推演平台配置

9月23开始&#xff0c;9月26完成。因为那时刚从大连回来&#xff0c;十一之后又一个紧急项目当项目负责人&#xff0c;所以隔了这么久才发出来。 我尝试进行制作平台AI&#xff0c;想在我的小平板上配好&#xff0c;最好还可以移植。于是我采用WSL&#xff08;windows自带的do…

万界星空科技MES系统中的生产调度流程

MES系统生产调度的目标是达到作业有序、协调、可控和高效的运行效果&#xff0c;作业计划的快速生成以及面向生产扰动事件的快速响应处理是生产调度系统的核心和关键。 为了顺利生成作业计划&#xff0c;需要为调度系统提供完整的产品和工艺信息&#xff0c;MES系统生成作业计…

打工人副业变现秘籍,某多/某手变现底层引擎-Stable Diffusion 局部重绘(利用SD进行换脸)

首先明确一个概念:绘图是对整个图片进行重绘,但局部重绘是对你选中的位置重绘,这就是两个功能的不同点。 局部重绘详细步骤: 1、用画笔涂黑你想修改的地方,图片右边的蓝色点可以拖动 改变画笔大小,边缘适合用小画笔,中间用粗画笔; 2、在正向关…

C语言普里姆(Prim)算法实现计算国家建设高铁运输网最低造价的建设方案

背景&#xff1a; 描述&#xff1a;为促进全球更好互联互通&#xff0c;亚投行拟在一带一路沿线国家建设高铁运输网&#xff0c;请查阅相关资料 画出沿线国家首都或某些代表性城市的连通图&#xff0c;为其设计长度最短或造价最低的高铁建设方案。 要求&#xff1a;抽象出的图…

实战React18和TS+Vite,跟进实战阅读类App的心得分享

随着 React 18 的发布&#xff0c;以及 TypeScript 和 Vite 在前端开发领域的普及&#xff0c;使用 React 18 结合 TypeScript 和 Vite 开发实战阅读类 App 的经验已经成为了前端开发者们的热门话题。在本文中&#xff0c;我将分享我的心得体会&#xff0c;并给出一些示例代码&…

深度学习第5天:GAN生成对抗网络

☁️主页 Nowl &#x1f525;专栏 《深度学习》 &#x1f4d1;君子坐而论道&#xff0c;少年起而行之 ​​ 一、GAN 1.基本思想 想象一下&#xff0c;市面上有许多仿制的画作&#xff0c;人们为了辨别这些伪造的画&#xff0c;就会提高自己的鉴别技能&#xff0c;然后仿制者…

【EI征稿倒计时3天】第四届IEEE信息科学与教育国际学术会议(ICISE-IE 2023)

第四届IEEE信息科学与教育国际学术会议(ICISE-IE 2023) 2023 4th International Conference on Information Science and Education&#xff08;ICISE-IE 2023&#xff09; ICISE-IE2024已上线岭南师范学院官网&#xff08;点击查看&#xff09; 第四届IEEE信息科学与教育国…

【JavaEE学习】初识进程概念

个人主页&#xff1a;兜里有颗棉花糖 欢迎 点赞&#x1f44d; 收藏✨ 留言✉ 加关注&#x1f493;本文由 兜里有颗棉花糖 原创 收录于专栏【Java系列】【JaveEE学习专栏】 本专栏旨在分享学习JavaEE的一点学习心得&#xff0c;欢迎大家在评论区交流讨论&#x1f48c; 目录 一、…

IoTDB控制台工具Workbench

文章目录 概述环境要求安装下载启动服务 登录用户界面主界面 连接 概述 Workbench是一个可创建多个连接的图形化数据库管理工具&#xff0c;用于管理IoTDB&#xff0c;提供元数据的可视化与管理、数据的增删改查以及权限控制等功能。Workbench不仅满足专业开发人员的所有需求&…

【lesson7】数据类型之string类型

文章目录 数据类型分类string类型set类型测试 enum类型测试 string类型的内容查找找所有女生&#xff08;enum中&#xff09;找爱好有游泳的人&#xff08;set中&#xff09;找到爱好中有足球和篮球的人 数据类型分类 string类型 set类型 说明&#xff1a; set&#xff1a;集…

Qt 使用百度的离线地图

使用百度离线地图&#xff0c;一下载百度离线包&#xff08;offlinemap&#xff09;&#xff1b;二是准备地图瓦片&#xff08;不同级别的瓦片&#xff09;&#xff1b;三 准备&#xff48;&#xff54;&#xff4d;&#xff4c;主页面&#xff1b;四&#xff0c;&#xff31;&…

免费提升图片清晰度的AI平台,效果对比一目了然!

随着AI技术的不断发展&#xff0c;我们有了更多的机会去挖掘和提升图片清晰度的可能性。无论是老照片的翻新、档案的修复&#xff0c;还是遥感图像的处理、医学影像的分析&#xff0c;AI都能大显身手。在过去可能很难办到的将分辨率低的图片转为高清图&#xff0c;如今借助AI简…

CLIP的升级版Alpha-CLIP:区域感知创新与精细控制

为了增强CLIP在图像理解和编辑方面的能力&#xff0c;上海交通大学、复旦大学、香港中文大学、上海人工智能实验室、澳门大学以及MThreads Inc.等知名机构共同合作推出了Alpha-CLIP。这一创新性的突破旨在克服CLIP的局限性&#xff0c;通过赋予其识别特定区域&#xff08;由点、…

精通TypeScript:打造一个炫酷的天气预报插件

前言 ​ 随着数字化和信息化的发展&#xff0c;数据大屏使用越来越广泛&#xff0c;我们不仅需要展示数据&#xff0c;更需要以一种更加美观的方式展示数据。这就必然需要使用到各种图表组件&#xff0c;比如柱状图、饼图、折线图等等。但是有一些效果不太适合通过这种常规图表…

做数据分析为何要学统计学(5)——什么问题适合使用卡方检验?

卡方检验作为一种非常著名的非参数检验方法&#xff08;不受总体分布因素的限制&#xff09;&#xff0c;在工程试验、临床试验、社会调查等领域被广泛应用。但是也正是因为使用的便捷性&#xff0c;造成时常被误用。本文参阅相关的文献&#xff0c;对卡方检验的适用性进行粗浅…

【Go】基于GoFiber从零开始搭建一个GoWeb后台管理系统(一)搭建项目

前言 最近两个月一直在忙公司的项目&#xff0c;上班时间经常高强度写代码&#xff0c;下班了只想躺着&#xff0c;没心思再学习、做自己的项目了。最近这几天轻松一点了&#xff0c;终于有时间 摸鱼了 做自己的事了&#xff0c;所以到现在我总算是搭起来一个比较完整的后台管…

血的教训,BigDecimal踩过的坑

很多人都用过Java的BigDecimal类型&#xff0c;但是很多人都用错了。如果使用不当&#xff0c;可能会造成非常致命的线上问题&#xff0c;因为这涉及到金额等数据的计算精度。 首先说一下&#xff0c;一般对于不需要特别高精度的计算&#xff0c;我们使用double或float类型就可…

微服务黑马头条(简略笔记)

Linux中nacos的拉取安装 拉取naocs镜像&#xff1a;docker pull nacos/nacos-server:1.2.0创建容器&#xff1a;docker run --env MODEstandalone --name nacos --restartalways -d -p 8848:8848 nacos/nacos-server:1.2.0访问地址&#xff1a;http://192.168.200.130:8848/n…