1.mybatis自带缓存功能。分为一级缓存,二级缓存。
2.一级缓存为 session 缓存,在一个 session中 ,一个查询的 select 语句只会执行一次,根据 <select></select>语句的id来判断。
@Test public void testFind() throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); User user = (User)session.selectOne("cn.sxt.vo.UserMapper.findUser",1); System.out.println(user); System.out.println("==========================="); User u=(User)session.selectOne("cn.sxt.vo.UserMapper.findUser",1); System.out.println(u); session.close(); }
3.二级缓存,是 sessionFactory 级别的缓存,在 mybatis 中实现二级缓存的步骤
a) 首先实体类要序列化,二级缓存存储的是数据文件
b) 在映射中添加 cache 标签
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
代码
@Test public void testFind() throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); User user = (User)session.selectOne("cn.sxt.vo.UserMapper.findUser",1); System.out.println(user); session.close(); System.out.println("==========================="); session = MybatisUtil.getSqlSession(); User u=(User)session.selectOne("cn.sxt.vo.UserMapper.findUser",1); System.out.println(u); session.close(); }
附:
UserMapper.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.sxt.vo.UserMapper"> <select id="findUser" resultType="User"> select * from t_user where id=#{id} </select> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> </mapper>