浅谈MyBatis缓存
发布日期:2021-05-07 13:38:20 浏览次数:14 分类:原创文章

本文共 3730 字,大约阅读时间需要 12 分钟。

学过MyBatis框架的都知道,MyBatis自带一二级缓存,并且还有第三方给MyBastis提供二级缓存,例如ehcache、memcache,本文粗略的讲一下这个几个缓存的机制和使用吧。
首先解释一下缓存存在的意义:他避免了相同的sql查询语句频繁的去访问数据库。自动的把第一次查询的结果放在了缓存中,后续再次查询该同样的对象时,则直接从缓存中查询该对象即可。
一级缓存:
MyBatis默认开启一级缓存,范围是同一个SqlSession对象。

public static void query() throws IOException {       Reader reader = Resources.getResourceAsReader("conf.xml");    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);    SqlSession session = sessionFactory.openSession();        StudentMapper studentMapper = session.getMapper(StudentMapper.class);    Student3 student1 = studentMapper.queryStudentByStuno(1);    Student3 student2 = studentMapper.queryStudentByStuno(1);    System.out.println(student1.getStuNo()+","+student1.getStuName());    System.out.println(student2.getStuNo()+","+student2.getStuName());    session.close();}

比如上面的代码,student1和student2来自同一个SqlSession产生的StudentMapper,所以共享了缓存。开启日志发现明显只执行了一条sql语句:
在这里插入图片描述这里补充说明一下:执行commit()语句会清除一级缓存,比如在上面的代码中加上这一样一行:

Student3 student1 = studentMapper.queryStudentByStuno(1);session.commit();Student3 student2 = studentMapper.queryStudentByStuno(1);

执行就会发现MyBatis执行了两条sql语句,缓存被清理了:
在这里插入图片描述
二级缓存
开启二级缓存需要手动开启,范围是同一个namespace:
需要三步配置:
1.在MyBatis核心配置文件中加入配置信息:

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

2.在具体的Mapper.xml中加入,表明该接口开启了二级缓存!

<cache/>

如果想某个标签体不使用二级缓存,可以在相应的< select >中加上属性useCache=“false”!
3.准备缓存的对象,必须实现了序列化接口,将用到的实体类implements Serializable!(级联属性也需要序列化)

下面开始说使用的问题:
二级缓存不是自动将第一个sql语句放入缓存,需要session.close()语句将sql语句刷进缓存。

public static void query() throws IOException {       Reader reader = Resources.getResourceAsReader("conf.xml");    //可以通过build的第二个参数环境  指定数据库环境    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);    SqlSession session = sessionFactory.openSession();    StudentMapper studentMapper = session.getMapper(StudentMapper.class);    Student3 student3 = studentMapper.queryStudentByStuno(2);    session.close();    //第二次查询    SqlSession session2 = sessionFactory.openSession();    StudentMapper studentMapper2 = session2.getMapper(StudentMapper.class);    Student3 student4 = studentMapper2.queryStudentByStuno(2);    session2.close();    System.out.println(student3.getStuNo()+","+student3.getStuName());    System.out.println(student4.getStuNo()+","+student4.getStuName());}

可以看出上面的查询语句来源的并不是同一个SqlSession对象,但却都从StudentMapper.class的反射(也就是同一个namespace)获取动态代理对象studentMapper!
在这里插入图片描述
如果删掉session.close()语句,则运行结果是这样的:
在这里插入图片描述
同样可以用commit()语句清除缓存,但需要注意的是不能是查询自身的commit,需要用增删改语句的commit来清除。还可以在mapper.xml文件中的< select >标签中增加属性 flushCache="true"来自动清除缓存!

再说一下第三方提供的二级缓存(ehcache):

1.导入三个jar:ehcache-core.jar,mybatis-ehcache.jar和self-api.jar
在这里插入图片描述
2.编写Ehcache.xml并放在内路径中:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">    <diskStore path="F:\Ehcache"/>    <!--    maxElementsInMemory:设置在内存中缓存对象的个数    maxElementsOnDisk:设置 在硬盘中缓存 对象的个数    eternal:设置缓存是否不过期    overflowToDisk:当内存中缓存的对象个数 超过maxElementsInMemory的时候,是否转移到银盘    timeToIdleSeconds:当2次访问 超过该值的时候(单位s) 将缓存对象失效    timeToLiveSeconds:一个缓存对象 最多存放的时间(生命周期)    diskExpiryThreadIntervalSeconds:设置每隔多长时间,通过一个线程来清理硬盘中的缓存    memoryStoreEvictionPolicy:当超过缓存    -->    <defaultCache            maxElementsInMemory="1000"            maxElementsOnDisk="1000000"            eternal="false"            overflowToDisk="false"            timeToIdleSeconds="100"            timeToLiveSeconds="100"            diskExpiryThreadIntervalSeconds="120"            memoryStoreEvictionPolicy="LRU">    </defaultCache></ehcache>

3.其余的配置和Mybatis自带的二级缓存差不多!唯一需要注意的是具体的mapper.xml中不再是配置< cache />,而是:

<cache type="org.mybatis.caches.ehcache.EhcacheCache">    <!--<property name="maxElmentsInMemory" value="2000"/>--></cache>
上一篇:PY爬取2020年电影票房排行
下一篇:怎么玩LOG4J

发表评论

最新留言

很好
[***.229.124.182]2025年03月28日 22时22分08秒