一. 例子
EmployeeMapperCache.java
package com.atguigu.mybatis.dao;
import com.atguigu.mybatis.beans.Employee;
public interface EmployeeMapperCache {
public Employee selectEmployeeById(Integer id);
}
EmployeeMapperCache.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.atguigu.mybatis.dao.EmployeeMapperCache">
<!-- public Employee selectEmployeeById(Integer id); -->
<select id="selectEmployeeById" resultType="com.atguigu.mybatis.beans.Employee">
select id, last_name, email, gender from tbl_employee where id = #{id}
</select>
</mapper>
TestMyBatisCache.java
package com.atguigu.mybatis.test;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.atguigu.mybatis.beans.Employee;
import com.atguigu.mybatis.dao.EmployeeMapperCache;
import com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL;
public class TestMyBatisCache {
/**
* 一级缓存(本地缓存):
* 1. 一级缓存默认是开启的
* 2. 一级缓存是SqlSession级别的缓存。每一个SqlSession对象都有自己的一级缓存
* 3. 一级缓存的工作机制:
* 一个SqlSession对象第一次查数据,会从数据库中把对应的数据查询到,
* 并且会将查询到的数据保存到当前SqlSession对象的一级缓存中。再使用
* 当前的SqlSession对象进行后续的查询相同的数据,都可以从一级缓存中获取到对应
* 的数据。
* 4. 实际上一级缓存就是一个Map。key:hashCode+查询的SqlId+编写的sql查询语句+参数
*
*/
@Test
public void testFirstLevelCache() throws Exception{
SqlSessionFactory ssf = getSqlSessionFactory();
SqlSession session = ssf.openSession();
try {
EmployeeMapperCache mapper = session.getMapper(EmployeeMapperCache.class);
Employee employee1 = mapper.selectEmployeeById(1001);
System.out.println("employee1:" + employee1);
System.out.println("------------------------------------------");
Employee employee2 = mapper.selectEmployeeById(1001);
System.out.println("employee2:" + employee2);
session.commit();
} finally {
// TODO: handle finally clause
session.close();
}
}
public SqlSessionFactory getSqlSessionFactory() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream =
Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory;
}
}