关于mybatis二级缓存疑问
在一级缓存及二级缓存都有需要的查询的数据时是先访问二级缓存还是一级缓存?(目前答案是先访问二级缓存)
示例代码如下:
package dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import pojo.User;
import utils.MybatisUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserDaoTest {
@Test
public void test(){
//获得sqlsession对象
SqlSession sqlSession= MybatisUtils.getSqlSession();
//执行SQL
UserDao userDao=sqlSession.getMapper(UserDao.class);
HashMap map=new HashMap();
map.put("id",2);
List<User> userList=userDao.getUserList(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
//此时List<User>丢入二级缓存
SqlSession sqlSession2= MybatisUtils.getSqlSession();
UserDao userDao2=sqlSession2.getMapper(UserDao.class);
HashMap map2=new HashMap();
map.put("id",2);
List<User> userList2=userDao2.getUserList(map);
for (User user : userList2) {
System.out.println(user);
}
//此时一级缓存有List<User>
SqlSession sqlSession3= MybatisUtils.getSqlSession();
UserDao userDao3=sqlSession3.getMapper(UserDao.class);
HashMap map3=new HashMap();
map.put("id",2);
//此时获得二级还是一级缓存对象?
List<User> userList3=userDao3.getUserList(map);
for (User user : userList3) {
System.out.println(user);
}
sqlSession2.close();
sqlSession3.close();
}
}
关于mybatis缓存图解如下(引用):