在MyBatis中,一级缓存是默认开启的。
1、在一个SqlSession中,对User表进行两次根据ID的查询,查看发出sql语句的情况。
/**
* 根据ID查询用户
*
* @param id
* @return
*/
@Select("select * from user where id=#{id}")
User findUserById(Integer id);
@Before
public void before() throws Exception {
System.out.println("before...");
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//根据 sqlSessionFactory 产生 session
sqlSession = sqlSessionFactory.openSession();
// 这样也是可以的,这样的话后面就不用每次都设置了
// sqlSession = sqlSessionFactory.openSession(true);
userMapper = sqlSession.getMapper(IUserMapper.class);
}
@Test
public void testFindUserById() {
//第一次查询,发出sql语句,并将查询出来的结果放进缓存中
User user = userMapper.findUserById(1);
System.out.println(user);
//第二次查询,由于是同一个sqlSession,会在缓存中查询结果 //如果有,则直接从缓存中取出来,不和数据库进行交互
User user2 = userMapper.findUserById(1);
System.out.println(user2);
}
sql执行过程如下:
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1677d1]
==> Preparing: select * from user where id=?
==> Parameters: 1(Integer)
<== Columns: id, username, password, birthday
<== Row: 1, lucy, 123, 2019-12-12
<== Total: 1
User{id=1, username='lucy', orderList=null, roleList=null}
User{id=1, username='lucy', orderList=null, roleList=null}
Process finished with exit code 0
标签:缓存,一级,查询,sqlSession,sqlSessionFactory,User,MyBatis,id From: https://www.cnblogs.com/tangyouwei/p/mybatis-s-first-level-cache-zzbwpu.html