mybatis一级缓存
mybatis一级缓存: 在同一个sqlsession中,查询语句相同且查询参数相同,第二次查询时取缓存的数据
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.mgr.user.po.UserPO;
//mybatis一级缓存
public class SessionTest {
public static void main(String[] args)throws Exception{
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
DefaultSqlSessionFactory factory = (DefaultSqlSessionFactory)app.getBean("sqlSessionFactory");
mybatisFirstCache(factory); //一级缓存:必须在同一个会话里
//mybatisFirstCache2(factory);
//mybatisFirstCache3(factory);
}
/**
* mybatis一级缓存: 同一个会话里的sql会缓存:
* 查询语句相同且查询参数相同,第二次在同一个会话里取缓存的结果
* @param factory
*/
static void mybatisFirstCache(DefaultSqlSessionFactory factory){
SqlSession session = factory.openSession();
String statement = "cn.mgr.user.mapper.UserMapper.findByID";
UserPO user = new UserPO();
user.setUserId(100);
UserPO u = session.selectOne(statement, user);
System.out.println("第一次查询:"+u.getUserName());
user = new UserPO();
user.setUserId(100);
u = session.selectOne(statement, user);
System.out.println("第二次查询:"+u.getUserName());
session.close();
}
/**
* mybatis一级缓存: 同一个会话里的sql会缓存:
* 查询语句相同且查询参数不同,第二次仍然会查询数据库
* @param factory
*/
static void mybatisFirstCache2(DefaultSqlSessionFactory factory){
SqlSession session = factory.openSession();
String statement = "cn.mgr.user.mapper.UserMapper.findByID";
UserPO user = new UserPO();
user.setUserId(100);
UserPO u = session.selectOne(statement, user);
System.out.println("第一次查询:"+u.getUserName());
user = new UserPO();
user.setUserId(101);
u = session.selectOne(statement, user);
System.out.println("第二次查询:"+u.getUserName());
session.close();
}
/**
* mybatis一级缓存: 不同的会话
* 查询语句相同且查询参数不同,第二次仍然会查询数据库
* @param factory
*/
static void mybatisFirstCache3(DefaultSqlSessionFactory factory){
SqlSession session = factory.openSession();
String statement = "cn.mgr.user.mapper.UserMapper.findByID";
UserPO user = new UserPO();
user.setUserId(100);
UserPO u = session.selectOne(statement, user);
System.out.println("第一次查询:"+u.getUserName());
session.close();
session = factory.openSession();
user = new UserPO();
user.setUserId(100);
u = session.selectOne(statement, user);
System.out.println("第二次查询:"+u.getUserName());
session.close();
}
}
上一篇: mybatis使用实例