其他分享
首页 > 其他分享> > 二级缓存

二级缓存

作者:互联网

二级缓存作用域在Mapper中。当一级缓存失效后,一级缓存中的数据会转移到二级缓存中

1.在Mybatis中开启二级缓存

<setting name="cacheEnabled" value="true"/><!--开启二级缓存-->

2.在Mapper.xml中

<cache/><!--在Mapper中开启二级缓存-->

3.测试

    public void getUserById (){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();

        userMapper mapper = sqlSession.getMapper(userMapper.class);


        user user1 = mapper.getUserById(2);//查找用户
        System.out.println(user1);
        sqlSession.close();
        System.out.println("=========");
        SqlSession sqlSession1 = sqlSessionFactory.getsqlSession();

        userMapper mapper1 = sqlSession1.getMapper(userMapper.class);
        user user2 = mapper1.getUserById(2);
        System.out.println(user2);
        sqlSession1.close();

    }

4.结果

Caused by: java.io.NotSerializableException: com.Google.pojo.user

解决方法
在实体类中继承序列化

public class user implements Serializable {
    private int id;
    private String name;
    private String pwd;
}

结果

Opening JDBC Connection
Created connection 1304589447.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4dc27487]
==>  Preparing: select * from user where id=? 
==> Parameters: 2(Integer)
<==    Columns: id, name, pwd
<==        Row: 2, aaa, bbb
<==      Total: 1
user(id=2, name=aaa, pwd=bbb)
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4dc27487]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4dc27487]
Returned connection 1304589447 to pool.
=========
Cache Hit Ratio [com.Google.mapper.userMapper]: 0.5
user(id=2, name=aaa, pwd=bbb)

这里可以看到,第一个sqlSession关闭后,缓存给了二级缓存,然后第二个sqlSession直接得到了来自缓存中的数据。这就是二级缓存(补充了一级缓存的缺点)

标签:缓存,userMapper,sqlSession,二级缓存,user,println
来源: https://www.cnblogs.com/luoking/p/15857625.html