zoukankan      html  css  js  c++  java
  • Mybatis缓存

    Mybatis有一级缓存和二级缓存。

    1.一级缓存是在SqlSession层的, 如果你使用同一个SqlSession来执行2次同一条查询语句,  第一次会建立连接从数据库中查询,第二次就直接从一级缓存中查询。Mybatis中默认开启一级缓存。

    注意, 如果是spring和mybatis集成的话,   spring会帮助我们关闭sqlsession,所以2次调用时2个sqlsession,  缓存没用到。

    但是,如果是在同一个事务之中,是使用同一个sqlsession,  第二次查询会返回缓存中的数据, 如果要强制不使用cache, 就要设置 flushCache="false"

    2.二级缓存是在SqlSessionFactory层的,open2个SqlSession, 执行同一条查询语句,第一次会建立连接从数据库中查询,第二次从二级缓存中查询。

    在日志中可以看到类似以下的内容,表示是从缓存中获取:

    DEBUG 2016-03-12 14:19:47,777 org.apache.ibatis.cache.decorators.LoggingCache: Cache Hit Ratio

    Mybatis默认关闭二级缓存,需要在配置文件中加入以下配置项进行开启:

    在全局配置中加入

    <setting name="cacheEnabled" value="true"/>

    在需要缓存的Mapper。xml中加入:

    <cache />

    并且要求缓存的POJO必须是可以序列化的,即必须实现Serializable接口。

    我们也可以配置SQL层面上的缓存规则,来决定他们是否需要使用或者刷新缓存。

    在select中使用缓存,不刷新缓存

    在insert,update,delete中刷新缓存

    配置如下:

    <select ... flushCache="false" useCache="true"?>

    <insert ...  flushCache="true"/>

    <update ...  flushCache="true"/>

    <delete ...  flushCache="true"/>

  • 相关阅读:
    array and ram
    char as int
    pointer of 2d array and address
    Install SAP HANA EXPRESS on Google Cloud Platform
    Ubuntu remount hard drive
    Compile OpenSSL with Visual Studio 2019
    Install Jupyter notebook and tensorflow on Ubuntu 18.04
    Build OpenCV text(OCR) module on windows with Visual Studio 2019
    Reinstall VirtualBox 6.0 on Ubuntu 18.04
    Pitfall in std::vector<cv::Mat>
  • 原文地址:https://www.cnblogs.com/yfdream/p/7866194.html
Copyright © 2011-2022 走看看