在同一个session中同sql语句和同参数的查询可以被缓存。
但是更改参数查询后再回来调用上一次的查询,缓存是否还在呢?
@Test
public void query(){
//此方法仅有的一个Session
SqlSession session = factory.openSession();
HouseDao houseDao = session.getMapper(HouseDao.class);
//分页条件(pageNo,size)
Map map = new HashMap();
map.put("pageNo", 0);
map.put("size", 5);
//第一次查询,发sql语句
System.out.println("query 1,查询1-5 -----------------");
List<House> houseList1 = houseDao.getHouse(map);
//第二次查询同参同sql,所以不发sql语句,从一级缓存里取
System.out.println("query 2,查询1-5 -----------------");
List<House> houseList2 = houseDao.getHouse(map);
//第三次查询6-10条记录,显然是不同参的sql,会重新查询
System.out.println("query 3,查询5-10 -----------------");
map.put("pageNo", 5);
map.put("size", 10);
List<House> houseList3 = houseDao.getHouse(map);
//第四次查询又是1-5条记录,所以它还会从缓存里取,不会发sql语句
System.out.println("query 4,查询1-5-----------------");
map.put("pageNo", 0);
map.put("size", 5);
List<House> houseList4 = houseDao.getHouse(map);
}
运行结果:
query 1,查询1-5 -----------------
2013-11-24 00:15:10,890 [main] DEBUG [com.dao.HouseDao.getHouse] - ooo Using Connection [com.mysql.jdbc.Connection@f07355]
2013-11-24 00:15:10,890 [main] DEBUG [com.dao.HouseDao.getHouse] - ==> Preparing: select h.id as hid,contact,description,floorage,price,pubdate,title, u.id as uid,u.isAdmin,u.name as uname,u.password,u.telephone,u.username, t.id as tid,t.name as tname, s.id as sid,s.name as sname, d.id as did,d.name as dname from house h left join type t on h.type_id = t.id left join street s on h.street_id = s.id left join district d on s.district_id = d.id left join users u on h.user_id = u.id order by h.price asc limit ?,?
2013-11-24 00:15:10,953 [main] DEBUG [com.dao.HouseDao.getHouse] - ==> Parameters: 0(Integer), 5(Integer)
2013-11-24 00:15:11,000 [main] DEBUG [com.dao.HouseDao.getHouse] - <== Total: 5
query 2,查询1-5 -----------------
query 3,查询5-10 -----------------
2013-11-24 00:15:11,000 [main] DEBUG [com.dao.HouseDao.getHouse] - ooo Using Connection [com.mysql.jdbc.Connection@f07355]
2013-11-24 00:15:11,000 [main] DEBUG [com.dao.HouseDao.getHouse] - ==> Preparing: select h.id as hid,contact,description,floorage,price,pubdate,title, u.id as uid,u.isAdmin,u.name as uname,u.password,u.telephone,u.username, t.id as tid,t.name as tname, s.id as sid,s.name as sname, d.id as did,d.name as dname from house h left join type t on h.type_id = t.id left join street s on h.street_id = s.id left join district d on s.district_id = d.id left join users u on h.user_id = u.id order by h.price asc limit ?,?
2013-11-24 00:15:11,000 [main] DEBUG [com.dao.HouseDao.getHouse] - ==> Parameters: 5(Integer), 10(Integer)
2013-11-24 00:15:11,015 [main] DEBUG [com.dao.HouseDao.getHouse] - <== Total: 10
query 4,查询1-5-----------------
1和2查询发了一次,3查询发了一次,4查询和1查询的sql和参数一样,所以没有重新发,所以发送过的sql语句及参数都会保留在缓存。