Mybatis的一级缓存机制简介
1.接口
public interface MemberMapperCache { public Members selectMembersById(Integer id); }
2.配置文件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="com.dao.MemberMapperCache"> <select id="selectMembersById" resultType="members"> select * from members where id = #{id} </select> </mapper>
3.测试类
/** * Mybatis的缓存机制 * 一级缓存(本地缓存)也叫sqlSession级别的缓存:与数据库同一次会话期间查询到的数据会放在本地缓存中,以后再获取相同的数据就没必要再去数据库中拿了 * 一级缓存失效的4种情况 * 1.sqlSession不同 * 2.sqlSession相同但是查询条件不同(很好理解) * 3.sqlSession相同但是两次查询之间掺杂了相同数据的增删改操作 * 4.sqlSession相同但是两次查询之间清除了缓存(session.clearCache();) */ public static void main(String[] args) throws IOException { SqlSession session = getSqlSession(); try { // 面向接口方式 MemberMapperCache mapper = session.getMapper(MemberMapperCache.class); Members member1 = mapper.selectMembersById(1); Members member2 = mapper.selectMembersById(2); System.out.println(member1.toString()); System.out.println(member2.toString()); session.commit(); } finally { // 关闭session session.close(); } } public static SqlSession getSqlSession() throws IOException { // 读取全局配置文件 String resource = "conf/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 获取sqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 打开session SqlSession session = sqlSessionFactory.openSession(); return session; }
4.打印结果
==> Preparing: select * from members where id = ? ==> Parameters: 1(Integer) <== Columns: id, member_name, pass_word, age <== Row: 1, 张三, 123456, 25 <== Total: 1 Member [id=1, member_name=张三, password=123456, age=25] Member [id=1, member_name=张三, password=123456, age=25]
两次相同查询可见只打印了一条sql语句,这就是本地缓存机制
5.清除缓存操作
MemberMapperCache mapper = session.getMapper(MemberMapperCache.class); Members member1 = mapper.selectMembersById(1); session.clearCache(); Members member2 = mapper.selectMembersById(1); System.out.println(member1.toString()); System.out.println(member2.toString());
结果
==> Preparing: select * from members where id = ? ==> Parameters: 1(Integer) <== Columns: id, member_name, pass_word, age <== Row: 1, 张三, 123456, 25 <== Total: 1 ==> Preparing: select * from members where id = ? ==> Parameters: 1(Integer) <== Columns: id, member_name, pass_word, age <== Row: 1, 张三, 123456, 25 <== Total: 1 Member [id=1, member_name=张三, password=123456, age=25] Member [id=1, member_name=张三, password=123456, age=25]
发送了两条sql语句